2015-08-14 23 views
0

我正試圖編寫一個程序,它從用戶指定的文件中讀取文本。現在,這個程序應該檢測到一個空行。如何檢測文件中的新行(或空行)?

這是我已經嘗試過失敗:

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); 
     } 
    } 
} 

更清楚:

如果我傳遞一個文本文件,例如這樣的文字:

TEST1
test2

test3

TEST4

它應該打印2名在因爲空空間的控制檯,但事實並非如此。

謝謝你的時間,我很高興你有任何建議。

+0

確切的輸出是什麼?它是否仍然打印換行符?你嘗試過調試嗎? –

回答

1

這是因爲比較是錯誤的。不能使用==比較兩個字符串,您需要使用equals方法:

if(line.equals("")) 

由於要檢查空字符串,你也可以寫

if(line.isEmpty()) 

How do I compare strings in java?

0

你做錯了什麼是你比較變量本身,而不是它的價值與空字符串。在類 一般有內置的功能,對於檢查返回真正 & 如果它的==的東西。

if(line.equals("")) { ... } 

或者您可以使用任何替代方法。

1

BackSlash是完全正確的,並已回答您的問題。我想補充一點,你的代碼中有一些錯誤:

  • 你不關閉
  • 你不是測試第一線的空白
  • 你處理null值時,閱讀器達到EOF

以下內容更正了這些錯誤。

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 

注意:你還在印刷中除了 「一」 空行。

相關問題