Java Scanner Checking Tokens
Reading a file with Scanner
Following is the third program on Scanner (first one being reading from keyboard) that reads from a file with default delimiter and user-defined delimiter.
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.io.File;
public class FileReadingWithScanner
{
public static void main(String args[]) throws FileNotFoundException
{
File f1 = new File("RKMutt.txt");
Scanner scan = new Scanner(f1);
// using whitespace as delimiter which is default
System.out.println("\tReading and printing each word:");
while(scan.hasNext())
{
String s1 = scan.next();
System.out.println(s1);
}
scan.close();
// to use our own delimiter
Scanner scan1 = new Scanner(f1);
scan1.useDelimiter(System.getProperty("line.separator"));
System.out.println("\tReading and printing each line (not each word):");
while(scan1.hasNext())
{
String str = scan1.next();
System.out.println(str);
}
scan1.close();
}
}
Output screenshot on Java Scanner Checking Tokens
File f1 = new File("RKMutt.txt");
Scanner scan = new Scanner(f1);
A File object, f1 representing the text file RKMutt.txt is passed as parameter to the Scanner constructor. The scan object checks each word in the file taking whitespace as delimiter.
Scanner scan1 = new Scanner(f1);
scan1.useDelimiter(System.getProperty("line.separator"));
The scan1 object treats line seprator (obtained by typing entering key in the source file) as the delimiter. For this reason, the hasNext() method in the second while loop treats the whole line as a single word and next() method reads the whole line (and not each word as in the earlier while loop).