我有以下格式的檔案:
姓名:John
文本:Hello
--empty line -- Buffered Reader 正在閱讀此內容。
名稱:Adam
文本:Hi
--empty line-- Buffered Reader 正在跳過這一行。
我嘗試了多種方法來讀取最后一個空行,但它不起作用。有什么建議?我有一個程式可以驗證訊息的格式是否正確。對于正確的格式,首先應該有三行名稱,然后是文本和空行。由于 BufferedReader 沒有讀取最后一個空行,我的程式總是說訊息格式錯誤。
我正在使用的示例代碼:
File file = new File(absolutePath);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
process(line);
}
uj5u.com熱心網友回復:
代碼正在按預期的方式作業。最后(空)行是檔案結尾(EOF)。有效行由回車和換行終止。因此,第 3 行被讀取。我包含了顯示文本和符號的檔案影像(為此使用了 Notepad )

如果我在末尾添加另一個空白行,請注意之前的空白行現在是如何終止的。

我稍微修改了你的代碼來運行這個場景
public static void main (String[] args) throws IOException {
File file = new File("emptyline.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
int linenum = 1;
while ( (line = br.readLine()) != null) {
System.out.println("Line " (linenum ) ": " line);
}
br.close();
}
當我在最后運行帶有兩個空行的代碼時,結果如下:
Line 1: Name: John
Line 2: Text: Hello
Line 3:
Line 4: Name: Adam
Line 5: Text: Hi
Line 6:
如果您有軟體可以根據以這種方式構建的資料來驗證此檔案,我不知道該說什么。這似乎是驗證檔案的不好方法。有更有效的方法可以做到這一點,例如使用校驗和。也許如果您嘗試在最后使用兩個空行,驗證器將接受它作為正確的格式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/416886.html
標籤:
上一篇:FIle.Copy()輸出mscorlib.dll中出現“System.UnauthorizedAccessException”型別的未處理例外
下一篇:無法讀取JSON嵌套檔案
