filereader—为什么java缓冲读取器在作为输入输出的大型txt文件中漏掉了很多行?

ffvjumwh  于 2021-07-13  发布在  Java
关注(0)|答案(4)|浏览(373)

嗨,我使用以下代码

public class Readfiles {

    FileInputStream fr;

    public void readAll(){

    try {
        fr = new FileInputStream(new File("books/Artificial intelligence.txt"));

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        System.out.println("File Not Found");
        e.printStackTrace();
    }
     CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
     decoder.onMalformedInput(CodingErrorAction.IGNORE);

    InputStreamReader reader = new InputStreamReader(fr, decoder);
    BufferedReader br = new BufferedReader(reader);

        try {
            int i = 0;

             for(String newLine; (newLine = br.readLine()) != null; )
                {

                newLine = br.readLine();

                i++;

                System.out.println(newLine);    
            }
            br.close();
            System.out.println(i);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
要读取这个txt文件,它大约有420.000行长:artificial intelligence.txt
但是我上面的代码没有正确读取它中间缺少大约一半的行,并且似乎从任何地方开始(每个都是随机开始的)下面是sysout的可能结果之一:
仅第一行:


# @Margaret H. Szymanski,Paul M. Aoki,Rebecca E. Grinter,Amy Hurst,James D. Thornton,Allison Woodruff

# cComputer Supported Cooperative Work

# %5488

# %87739

# %257074

# %818174

# !

# *Unpacking Tasks: The Fusion of New Technology with Instructional Work.

# t2008

# index831790

# %174882

# !

所以问题是为什么?
i的打印输出总是209647。

798qvoo8

798qvoo81#

你已经读了两遍了
一次

for(String newLine; (newLine = br.readLine()) != null; )
            {

然后又进来了

newLine = br.readLine();

那就更好了

while ((newLine = br.readLine()) != null) {....}
izj3ouym

izj3ouym2#

你在打电话吗 br.readLine() 在循环中执行两次,但仅使用循环中这两个调用之一的结果 System.out.println 打电话。所以你只打印每一行。

0qx6xfy6

0qx6xfy63#

你在打电话吗 br.readLine() 两次

for(String newLine; (newLine = br.readLine()) != null; )
{

    newLine = br.readLine();

    i++;

    System.out.println(newLine);    
}

你可以去掉循环中的那个

for(String newLine; (newLine = br.readLine()) != null; )
{

    i++;

    System.out.println(newLine);    
}
xyhw6mcr

xyhw6mcr4#

for(String newLine; (newLine = br.readLine()) != null; )
        {

            i++;

            System.out.println(newLine);
        }

相关问题