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

java bufferedReader.readLine() can't read whole file line

我们的后端程序读取 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也是部分执行的

OS : 红帽 7.4

java 版本:1.7.0_181

该行为的可能原因是您的程序在文件上传仍在进行时开始读取。为避免这种情况,您应该确保您的程序只读取完全传输的文件。如果你对上传过程有任何影响,让上传者使用一个临时文件名(被reader忽略),然后在传输后重命名文件。如果那不可能,您可以在阅读前检查文件的完整性(如果文件结尾清晰可辨),或者在文件出现后等待一段时间再开始阅读。最后一个选项可能是最容易实现的,但是将延迟设置得足够长以确保安全完成传输需要一些猜测。

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