2012-04-30 5 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); 
} 
関連する問題