Java 扫描流(Scanner)

在Scanner类里定义以下两个方法:

·判断是否有指定数据:public boolean hasNextXxx();

·取出数据:public 数据类型 nextXxx()

范例1:以键盘输入数据为例

import java.util.Scanner;

public class Demo {
	public static void main(String[] args) throws Exception {// 此处直接抛错
		Scanner scan = new Scanner(System.in);
		System.out.println("请输入内容:");
		if (scan.hasNext()) {
			System.out.println("输入的内容是:" + scan.next());
		}
		scan.close();
	}

}

Java 扫描流(Scanner)_第1张图片

============分割线============

范例2:正则验证

import java.util.Scanner;

public class Demo {
	public static void main(String[] args) throws Exception {
		Scanner scan;
		System.out.println("请输入你的生日:");
		boolean flag = true;
		while (flag) {
			scan = new Scanner(System.in);
			if (scan.hasNext("\\d{4}-\\d{2}-\\d{2}")) {
				String str = scan.next("\\d{4}-\\d{2}-\\d{2}");
				System.out.println("格式正确!您的生日是:" + str);
				flag = false;
			} else {
				System.out.println("格式错误!请重新输入:");
			}
		}
	}

}
Java 扫描流(Scanner)_第2张图片

============分割线============

范例3:读取文件

import java.io.File;
import java.io.FileInputStream;
import java.util.Scanner;

public class Demo {
	public static void main(String[] args) throws Exception {// 此处直接抛错
		Scanner scan = new Scanner(
				new FileInputStream(new File("e:" + File.separator + "demo" + File.separator + "my.txt")));
		scan.useDelimiter("\n");// 设置分隔符
		while (scan.hasNext()) {
			System.out.println(scan.next());
		}
		scan.close();

	}

}

你可能感兴趣的:(Java,IO高级应用)