Scanner nextline() only printing new lines

I'm trying to use scanner to print lines from a text file, but it only prints first line before printing only new lines until while loop goes through file.

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
}

How can I get System.out.println() to work with this code?


This is the Javadoc for nextLine()

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

You want next() instead:

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

Your code becomes:

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

您可以使用.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);
}
链接地址: http://www.djcxy.com/p/17212.html

上一篇: 扫描仪使用next()或nextFoo()后跳过nextLine()?

下一篇: 扫描仪nextline()仅打印新行