2014-05-09 28 views
0

我讀文件的Java,使用此代碼:在java中讀取文件時如何檢測我們有一行?

File file = new File(--path-); 

Scanner reader= new Scanner(file); 

while(reader.hasNext()){ 

    // i want to add here if reader.Next() == emptyline 
    // I tried if reader.Next()=="" but it did not work. 

} 

謝謝大家

+0

你試過了嗎if(reader.hasNextLine())'?請閱讀[API文檔](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#hasNextLine()) – BackSlash

回答

0

下一個()讀取文字和跳過空白。

我建議你使用

while(reader.hasNextLine()) { 
    String line = reader.nextLine(); 
    if(line.isEmpty()) { ... 
0

嘗試尋找http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine()

String line = reader.nextLine(); 
while (line != null) { 

    if (line.length() == 0) { 
    System.out.println ("zero length line"); 
    } 
    else { 
    System.out.println (line); 
    } 
    line = reader.nextLine(); 
} 

while (reader.hasNextLine()) { 

    line = reader.nextLine(); 
    if (line.length() == 0) { 
    System.out.println ("zero length line"); 
    } 
    else { 
    System.out.println (line); 
    } 

} 
0

如果你只需要閱讀所有的線,你可以簡單地使用:

List<String> lines = Files.readAllLines(path, charset); 
相關問題