![](/img/trans.png)
[英]Does Java's BufferedReader.readLine() put the whole file in memory?
[英]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.