在java中读取文本文件 - 为什么跳过行? [英] Reading a text file in java--why is it skipping lines?

查看:190
本文介绍了在java中读取文本文件 - 为什么跳过行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的,只是努力尝试阅读文本文件。在每一行上都有一个单词和相应的数字代码。我们的想法是阅读它并将代码和单词放在单独的变量中。我对这个领域了解不多,但我一直在网上四处寻找以下内容:

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

问题是不读取文本文件的第一行。然后它每次都跳过一条线! (换句话说,只读取第1行,第3行,第5行,第7行等)

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)

如上所述,我是新人,我不喜欢我非常了解我在网上不同网站上看到的所有不同的东西(比如为什么一切都是bufferedThis或bufferedThat,或者如何正确使用所有的tokenizer东西)。我在不同的时间尝试了几个不同的东西,最后得到了这个。

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.

推荐答案

你的while循环吞下了一半的线条在你的文件中。

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

while (inFile.readLine()!=null)

读取一行,但不将其分配给任何内容。在循环之前声明 String 并以这种方式读取每一行。

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)

现在变量将在循环内可用,因此您无需在inFile.readLine()中调用循环。

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

这篇关于在java中读取文本文件 - 为什么跳过行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆