【问题标题】:How to read a file continuously?如何连续读取文件?
【发布时间】:2015-01-09 09:59:32
【问题描述】:

我想连续读取一个文件,我的意思是如果我找到一个文件结尾,我想从头开始读取它。所以我正在重置流,但它不起作用。这是我的代码。

 br = new BufferedReader(new FileReader("E:\\Abc.txt"));
        while(true)
        {

            sCurrentLine = br.readLine();
            if(sCurrentLine!=null)
                System.out.println(sCurrentLine);
            else
                br.reset();

        } 

谁能帮帮我。

【问题讨论】:

  • 什么不完全有效?
  • @Harry 我不明白,关于mark() 方法之前reset() 的任何想法

标签: java file bufferedreader


【解决方案1】:
br = new BufferedReader(new FileReader("E:\\Abc.txt"));
while(true) {
     sCurrentLine = br.readLine();
     if(sCurrentLine!=null) {
          System.out.println(sCurrentLine);
     } else {
          br.close();
          br = new BufferedReader(new FileReader("E:\\Abc.txt"));
     }
}

所以它将使用新的 BufferedReader 重新启动 :)

【讨论】:

    【解决方案2】:

    您最好的选择可能是在readLine() 返回null 时重新创建BufferedReader

    例如:

    String filename = "[filename]";
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    
    while (true) {
        String line = reader.readLine();
        if (line != null)
            // Use line
        else {
            reader.close();
            reader = new BufferedReader(new FileReader(filename));
        }
    }
    

    这样做的好处是始终直接从文件中读取,而不会一次在内存中存储太多文件,如果如您所说,它包含 5000 行,这可能是一个问题。

    【讨论】:

      【解决方案3】:

      在初始化br后添加br.mark(100);

      Marks the present position in the stream. Subsequent calls to reset()
      will attempt to reposition the stream to this point.
      

      开启参数readAheadLimit

      readAheadLimit 限制可读取的字符数 同时仍然保留标记。之后尝试重置流 读取达到此限制或超过此限制的字符可能会失败。极限值 大于输入缓冲区的大小将导致一个新的缓冲区 分配的大小不小于限制。因此大值 应谨慎使用。

      以下代码会不断打印文件/home/user/temp/reader.test的内容

          BufferedReader br = new BufferedReader(new FileReader("/home/user/temp/reader.test"));
          String sCurrentLine;
      
          br.mark(100);
          while(true)
          {
              sCurrentLine = br.readLine();
              if(sCurrentLine!=null)
                  System.out.println(sCurrentLine);
              else
                  br.reset();
          } 
      

      【讨论】:

      • 是的。 . ,这里 100 是什么,我在一个文件中有 5000 行,如果它到达末尾,它必须从第一个读取,但是如果我输入 100,我会得到异常。
      • readAheadLimit Limit on the number of characters that may be read while still preserving the mark. 因此,如果您知道文件中的字符数量,请进行相应的设置,或者将其设置为足够大的数字以确保安全。如果这不是一个选项,重新打开缓冲区将是最干净的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-17
      • 2015-07-21
      • 2020-05-25
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 2014-01-29
      相关资源
      最近更新 更多