2012-04-30 49 views
0

我試圖使用掃描儀從文本文件打印行,但它只打印第一行,然後纔打印新行,直到while循環經過文件。掃描儀nextline()只打印新行

String line; 
File input = new File("text.txt"); 
Scanner scan = new Scanner(input); 
while (scan.hasNext()) //also does not work with hasNextLine(), but additional error 
{ 
line = scan.nextLine(); 
System.out.println(line); 
//other code can see what is in the string line, but output from System.out.println(line); is just a new line 
} 

如何獲取System.out.println()以使用此代碼?

回答

1

這是nextLine()

此掃描器當前行的Javadoc,並返回跳過的輸入信息。此方法返回當前行的其餘部分,排除末尾的任何行分隔符。該位置設置爲下一行的開頭。

你想next()代替:

查找並從該掃描儀返回下一個完整標記。完整的令牌前後有與分隔符模式匹配的輸入。即使先前調用hasNext()返回true,該方法也可能在等待輸入進行掃描時阻塞。

您的代碼就變成了:

while (scan.hasNext()) 
{ 
    line = scan.next(); 
    System.out.println(line); 
} 
0

您可以使用的.next()方法

String line; 
File input = new File("text.txt"); 
Scanner scan = new Scanner(input); 
while (scan.hasNext()) //also does not work with hasNextLine(), but additional error 
{ 
    line = scan.next(); 
    System.out.println(line); 
}