java bufferedReader.readLine()无法读取整个文件行

时间:2018-10-24 11:32:03

标签: java bufferedreader nio

我们的后端程序读取txt文件并逐行处理某些内容。

用于逐行读取文件,它使用的是bufferedReader.readLine

但有时,bufferedReader每季度一次无法读取整行。

如果实际有 1000 行文件,readLine()只需读取1〜530。

我确定文件格式正确。当我尝试在此错误之后再次读取文件时,它可以完美读取整行。

此文件是通过 FTP 上传的,并且文件监视程序可以检测文件是否正在运行。

下面是代码:

String fromFilePath = "/DATA/EXAMPLE.TXT"; //upload filepath example
String toFilePath = "/DATA/PROC/EXAMPLE.TXT";  //filepath to move

//read file after moving to another directory, to avoid catching file by file watcher and file in target path never exist. 
Files.move(Paths.get(fromFilePath), Paths.get(toFilePath), java.nio.file.StandardCopyOption.REPLACE_EXISTING, java.nio.file.StandardCopyOption.ATOMIC_MOVE);

BufferedReader br = new BufferedReader((new InputStreamReader(new FileInputStream(toFilePath, "UTF-8")));
int fileRowCount = 0;
String readLineResult = null;

while(readLineResult = br.readLine() != null){
  fileRowCount++;

  doBusinessLogic(readLineResult);

}

log.info("file log count {}", fileRowCount);

//confirm process to solve this problem. 
br = new BufferedReader((new InputStreamReader(new FileInputStream(toFilePath, "UTF-8")));
int assertCount= 0;

while(br.readLine() != null){
  assertCount++;
}

//it always print 'true' when occuring error, although BufferedReader is initialized newly 
log.info("assert {}", assertCount==fileRowCount);

fileRowCount无法打印整个行号。当然,doBusinessLogic也被部分执行。

操作系统:redhat 7.4

java版本:1.7.0_181

2 个答案:

答案 0 :(得分:2)

该行为的可能原因是程序仍在上载文件时开始读取程序。为避免这种情况,您应确保程序仅读取完全传输的文件。如果您对上载程序有任何影响,请让上载者使用一个临时文件名(读者会忽略它),然后在传输后重命名该文件。如果无法做到这一点,则可以在读取之前检查文件的完整性(如果可以清楚地识别文件结尾),或者在文件出现后等待一段时间再开始读取。最后一个选项可能最容易实现,但是将延迟设置足够长的时间以确保安全完成传输需要一些猜测。

答案 1 :(得分:0)

在while循环中使用(readLineResult = br.readLine()) != null 读取文件时也可以使用try catch块。作为参考,您可以访问here