Reading a text file in java--why is it skipping lines?

梦想与她 提交于 2019-12-31 03:57:07

问题


I'm new here and just struggling with trying to get a text file read. On every line there is a word and a corresponding numeric code. The idea is to read it and put the code and word in separate variables. I don't know so much about this area, but I've been looking around online and came up with the following:

try{
    FileReader freader=new FileReader(f); 
    BufferedReader inFile=new BufferedReader(freader);
    while (inFile.readLine()!=null){
       String s=null;
       s=inFile.readLine();
       System.out.println(s);
               String[] tokens=s.split(" ");
       string=tokens[0];
       System.out.println(string);
       code=tokens[1];
       System.out.println(code);
       c.insert(string, code);
    }//end outer while
}//end try

The issue is that the first line of the text file isn't read. And then it skips a line every time! (In other words, only the 1st, 3rd, 5th, 7th lines, etc. are read)

As I said above, I'm new, and I don't know much about all the different things I saw on different sites online (like why everything is bufferedThis or bufferedThat, or how to use all the tokenizer things properly). I was trying a few different things at different times, and ended up with this.


回答1:


Your while loop is swallowing half the lines in your file.

while (inFile.readLine()!=null)

That reads a line, but doesn't assign it to anything. Declare a String before the loop and read each line this way.

String line;
while ((line = inFile.readLine()) != null)

Now the variable line will be available inside the loop, so you don't need to call inFile.readLine() in the loop.




回答2:


Your problem is that you are reading every line twice. One inside the while block, and one in the condition of the while.

Try this:

try{
    FileReader freader=new FileReader(f); 
    BufferedReader inFile=new BufferedReader(freader);
    String s;
    while ((s=inFile.readLine())!=null){       
       System.out.println(s);
        String[] tokens=s.split(" ");
       string=tokens[0];
       System.out.println(string);
       code=tokens[1];
       System.out.println(code);
       c.insert(string, code);
    }//end outer while
}//end try


来源:https://stackoverflow.com/questions/12886638/reading-a-text-file-in-java-why-is-it-skipping-lines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!