import java.util.Scanner; public class Example1 { public static void main(String[] args) { String input = "Hello World!"; Scanner sc = new Scanner(input); while (sc.hasNext()) { // check if there are more tokens System.out.println(sc.next()); // output each token } } }
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Example2 { public static void main(String[] args) { File file = new File("text.txt"); try { Scanner sc = new Scanner(file); while (sc.hasNext()) { // check if there are more tokens System.out.println(sc.next()); // output each token } } catch (FileNotFoundException e) { System.out.println("File not found."); // catch potential exception } } }In this example, we create a new Scanner object using a File input. The code uses a try-catch block to catch a FileNotFoundException that may occur if the file cannot be found. If the file is found, the code enters a while loop that checks for the presence of more tokens. The loop outputs each token until there are no more left. Scanner belongs to a standard Java package library called java.util.