Java 读取文件内容时出现意外输出
我在阅读文件内容时遇到一些问题。Java 读取文件内容时出现意外输出,java,Java,我在阅读文件内容时遇到一些问题。 虽然程序正在读取内容,但它正在从文件中跳过奇数行数据 文件示例: Czech Republic____06092015_091108 France____06092015_060256 Greece____06092015_073528 Hungary____06092015_093424 India____06092015_120741 Indonesia____06092015_140940 Kazakhstan____
虽然程序正在读取内容,但它正在从文件中跳过奇数行数据 文件示例:
Czech Republic____06092015_091108
France____06092015_060256
Greece____06092015_073528
Hungary____06092015_093424
India____06092015_120741
Indonesia____06092015_140940
Kazakhstan____06092015_095945
Mexico____06092015_061522
Turkey____06092015_100457
java.io.DataInputStream@1909752
France____06092015_060256
Hungary____06092015_093424
Indonesia____06092015_140940
Mexico____06092015_061522
但输出为:
Czech Republic____06092015_091108
France____06092015_060256
Greece____06092015_073528
Hungary____06092015_093424
India____06092015_120741
Indonesia____06092015_140940
Kazakhstan____06092015_095945
Mexico____06092015_061522
Turkey____06092015_100457
java.io.DataInputStream@1909752
France____06092015_060256
Hungary____06092015_093424
Indonesia____06092015_140940
Mexico____06092015_061522
我不明白它为什么以这种格式输出。我在输入文件中有行分隔符,这会导致问题吗
public class tst {
// Main method
public static void main(String args[]) {
// Stream to read file
FileInputStream fin;
int k = 0;
try {
// Open an input stream
fin = new FileInputStream(
"C:/Users/BOT2/Desktop/MC_WIth_DATA_Files.txt");
DataInputStream in1 = new DataInputStream(fin);
// Read a line of text
System.out.println(new DataInputStream(fin));
// Close our input stream
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
while (br1.readLine() != null) {// System.out.println(k);k++;
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
// Catches any error conditions
catch (IOException e) {
System.err.println("Unable to read from file");
System.exit(-1);
}
}
}
第一行由以下人员打印:
System.out.println( new DataInputStream(fin) );
它为您提供新数据输入流(fin).toString()的结果。
下一行按此格式打印,因为每个循环读取两行:
第一行while(br1.readLine()!=null){
第二行:System.out.println(br1.readLine());}
因此,您必须将代码更改为:
String line;
while ((line =br1.readLine()) != null){//System.out.println(k);k++;
System.out.println(line );
}
br1.close();
fin.close();
问题就在这里
while (br1.readLine() != null){
System.out.println(br1.readLine());
}
br1.close();
fin.close();
}
调用br1.readLine()时,它将读取当前行并移动光标位置以指向下一行。您两次调用此方法,导致您跳过其他行。每次迭代只能调用readLine()。您有两个错误。首先,出于某种原因打印出dataStream对象。摆脱:
// Read a line of text
System.out.println( new DataInputStream(fin) );
接下来,你扔掉几行文字。请尝试以下方法:
String line;
while ((line = br1.readLine()) != null){
System.out.println(line);
}
我建议使用更干净的代码,这样您和任何阅读它的人都会立即了解您正在做什么 试试这个:
Scanner read;
try{
read=new Scanner(new FileReader("your path"));
while(read.hasNext()){
System.out.println(read.nextLine);
}
read.close();
}
catch(FileNotFoundException e){
}
因为你每次迭代都要读两次。一个在while表达式中,另一个在println方法中,您最好删除所有注释。他们只提供了不正确或无用的信息。@EvanThank.。它起作用了。它正在检查问题..不应该有2 system.out.line,应该一次读取一行。