有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我们的后端程序读取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:redhat 7.4

java版本:1.7.0_181


共 (2) 个答案

  1. # 1 楼答案

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

  2. # 2 楼答案

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