2015-10-09 31 views
-1

我有一個關於nextLine()方法的問題。我知道它有時不會讀取一行,而是讀取行分隔符,例如<enter>.因此,您需要調用.nextLine()兩次以「吃」分隔線,然後獲取下一行。但是,這將如何工作在一個循環?我怎麼能用這種方法得到文件的最後一行?我應該使用next()嗎?java中nextLine的問題。

while (fileStream1.hasNextLine()){ 
     counterString = fileStream1.nextLine(); 
     ++lines;    
    }   
+2

你測試這一點,你看到一個問題嗎? – Ryan

+0

你認爲一條線是什麼? –

+0

你提到的有關nextline的問題將會發生在next()和nextInt()與掃描器的情況下,我從來沒有見過filestream的問題。 – NightsWatch

回答

0

只要你能寫這樣的事情:

while (fileStream1.hasNextLine()){ 
    counterString = fileStream1.nextLine(); 
    if(!counterString.toString().equal("\n")) 
     ++lines;    
} 
+0

等於* ...錯字 –

0

試試這個:

while (fileStream1.hasNextLine()){ 
    counterString = fileStream1.nextLine(); 

    if (counterString.Equals("\n") || 
     counterString.Equals("\r\n") || 
     counterString.Equals("\r")) { 
     continue; 
    } 

    ++lines;    
} 

要跳過只是\n\r\n,或\r

0

如果我們談論F.E.所有行特別是關於掃描器,next()將返回下一個令牌,通常是由空格分隔的任何單詞或字符。如果您需要非空行的話,大概是這樣的:

String s; 
String lastLine; 
int numOfNonEmptyLines = 0; 

while(scan.hasNextLine()) { 

    s = scan.nextLine(); 
    if(s.trim().isEmpty()) { 
     continue; 
    } 

    lastLine = s; 
    numOfNonEmptyLines++; 
    //do whatever you want with the line 
} 

lastLine //this is the last line...