Reading a text file in java--why is it skipping li

2019-03-02 17:33发布

问题:

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