/* * Example of Scanner * Be notified that class Scanner is in java.util * Scanner can be used to read from a file, but NOT for Writing */ import java.util.*; import java.io.*; // Because class File will be used... class Scanner_file{ public static void main(String args[]) { try{ //* >>> Read a file that delimited by space >>> afile contains some information Scanner sc = new Scanner(new File("afile.txt")); String s = ""; while(sc.hasNext()){ s = sc.next(); //s = sc.nextLine(); // >>> use nextLine() to read a line each time System.out.println(s); }//while sc.close(); //*/ /* >>> Read a String that delimited by string or symbol insted of space String input = "1 little, 2 little, 3 little, Indians"; //Scanner sc = new Scanner(input).useDelimiter("\\s*little\\s*"); // >>> \s means white space, * means zero or more times >>> then you don't need to use trim() Scanner sc = new Scanner(input).useDelimiter(","); // try little >>> use trim() to get rid of the spaces aside while(sc.hasNext()){ System.out.println(sc.next().trim()); }//while sc.close(); //*/ /* >>> Read a file with variable type >>> bfile contains integers Scanner sc = new Scanner(new File("ifile.txt")); int i; int sum = 0; while(sc.hasNextInt()){ i = sc.nextInt(); System.out.println("i = " + i); sum += i; }//while sc.close(); System.out.println("sum = " + sum); // Try also hasNextBoolean(), hasNextByte(), hasNextDouble(), hasNextFloat(), hasNextLong, hasNextShort()*/ // In corresponding with nextBoolean(), nextByte(), nextDouble(), nextFloat(), nextLing, nextShort() }catch(Exception e) { }//catch }//main }//Scanner_file