A Scanner breaks its input into tokens using a delimiter pattern, which matches whitespace by default.
The hasNext() method checks if the Scanner has another token in its input.
/**
* @author lautturi.com
* Java example: reading file using Scanner in java
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;
public class Lautturi {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("test.txt"));
StringBuilder sb = new StringBuilder();
while (scanner.hasNext()) {
sb.append(scanner.nextLine()).append("\n");
}
System.out.println("File text :" + sb);
}
}
The hasNext() method determines whether the input (file, string, keyboard and other input streams) has the next input item.
Scanner sc = new Scanner(new File("text.txt"));
System.out.println(sc.hasNext());
If test.txt is empty (space, tab, enter), the output result is false; otherwise true.
When the input is the keyboard, the method is blocked:
It will always wait for keyboard input
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
System.out.println("Input from keyboard:" + sc.next());
}