【问题标题】:why Java buffered reader missed a lot of lines in output large txt file as input?为什么 Java bufferedreader 在输出大文本文件中遗漏了很多行作为输入?
【发布时间】:2016-03-28 04:15:51
【问题描述】:

您好,我使用以下代码

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。

【问题讨论】:

  • 哦,你是对的愚蠢的失败,谢谢它已修复!

标签: java filereader


【解决方案1】:

嗯,你读了两遍

一次

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

然后在

            newLine = br.readLine();

更好会是

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 哦,你是对的愚蠢的失败,谢谢它已修复!
    【解决方案3】:

    你给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);    
    }
    

    【讨论】:

      【解决方案4】:
      for(String newLine; (newLine = br.readLine()) != null; )
              {
      
                  i++;
      
                  System.out.println(newLine);
              }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-28
        • 2020-10-17
        • 1970-01-01
        • 2018-06-15
        • 1970-01-01
        • 1970-01-01
        • 2013-01-11
        • 1970-01-01
        相关资源
        最近更新 更多