[英]How to detect new line(or empty line) in a file?
我正在嘗試編寫一個程序,該程序從用戶指定的文件中讀取文本。 現在,該程序應該檢測到一個空行。
這是我嘗試失敗的內容:
public static void editFile(String filePath) throws FileNotFoundException, IOException {
file = new File(filePath);
if(file.exists()) {
fileRead = new FileReader(file);
bufferedReader = new BufferedReader(fileRead);
String line = bufferedReader.readLine();
System.out.println(line);
while(line != null) {
line = bufferedReader.readLine();
if(line == "") {
//line = null;
System.out.println("a");
}
System.out.println(line);
}
}
}
更清楚地說:
如果我傳入的文本文件包含以下文本:
測試1
測試2
測試3
測試4
由於空格,它應該在控制台上打印2 a,但不是。
謝謝您的寶貴時間,我很高興收到您的任何建議。
這是因為比較是錯誤的。 您不能使用==
比較兩個字符串,需要使用equals
方法:
if(line.equals(""))
由於您要檢查的是空字符串,因此您還可以編寫
if(line.isEmpty())
BackSlash是完全正確的,並且已經回答了您的問題。 我想補充一點,您的代碼有一些錯誤:
null
值 以下內容糾正了這些錯誤。
public static void editFile(String filePath) throws IOException
{
File file = new File(filePath);
if (file.exists())
{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try
{
String line;
while ((line = bufferedReader.readLine()) != null)
{
if (line.isEmpty())
{
//line = null;
System.out.println("a");
}
System.out.println(line);
}
} finally {
bufferedReader.close();
}
}
}
輸出為:
test1
test2
a
test3
a
test4
注意:除了“ a”之外,您還在打印空白行。
您做錯的是您正在比較變量本身,而不是將其值與空字符串進行比較。 通常, 字符串類中具有內置的函數,這些函數返回true和false來檢查其是否等於==。
if(line.equals("")) { ... }
或者,您也可以使用任何其他方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.