繁体   English   中英

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也可以部分执行。

操作系统:redhat 7.4

Java版本:1.7.0_181

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM