gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:51:13 25 4
gpt4 key购买 nike

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

最佳答案

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

关于java bufferedReader.readLine() 无法读取整个文件行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52967894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com