JDK 1.5 新特性——Scanner
1 package bin.ykb; 2 3 import java.io.File; 4 import java.io.FileNotFoundException; 5 import java.util.Scanner; 6 7 public class Demo1 { 8 9 /** 10 * 具体看JDK文档 11 * 12 * @author yokoboy 13 * @throws FileNotFoundException 14 */ 15 public static void readFile() throws FileNotFoundException { 16 Scanner scanner = new Scanner(new File("C:\\1.txt")); 17 while (scanner.hasNext()) { 18 System.out.println(scanner.next()); 19 } 20 } 21 22 // 读取控制台输入 23 public static void readIn() { 24 Scanner scanner = new Scanner(System.in); 25 while (scanner.hasNext()) { 26 String s = scanner.nextLine(); 27 if (s.equals("#")) { 28 break; 29 } 30 System.out.println(s); 31 } 32 } 33 34 public static void readString() { 35 Scanner scanner = new Scanner("11g3").useDelimiter("g");// 跳过g 36 System.out.println(scanner.nextInt()); 37 System.out.println(scanner.nextInt()); 38 } 39 40 public static void demo1() { 41 String input = "1fish 2 fish red fish blue fish"; 42 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");// 跳过fish,无论fish前后有没有空格 43 System.out.println(s.nextInt()); 44 System.out.println(s.nextInt()); 45 System.out.println(s.next()); 46 System.out.println(s.next()); 47 s.close(); 48 } 49 50 public static void main(String[] args) throws FileNotFoundException { 51 readFile();// 读取文件 52 readIn();// 读取控制台输入 53 readString();//读取字符串 54 demo1();//API文档中的例子 55 56 } 57 }
转载请注明出处:
博客园_yokoboy
http://www.cnblogs.com/yokoboy/archive/2012/07/25/2608427.html