Java IO高级应用(缓冲输入流)

BufferReader类的继承结构及构造方法:

java.lang.Object

    |-java.io.Reader

        |-java.io.BufferReader

public BufferReader(Reader in)

范例1:键盘数据输入标准

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Demo {
	public static void main(String[] args) throws Exception {// 此处直接抛错
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("请输入数据:");
		String str = buf.readLine();// 以回车作为换行
		System.out.println("输入的内容是:" + str);
	}

}

Java IO高级应用(缓冲输入流)_第1张图片

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

范例2:判断输入内容

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Demo {
	public static void main(String[] args) throws Exception {// 此处直接抛错
		BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
		boolean flag = true;
		while (flag) {
			System.out.println("请输入内容:");
			String str = buf.readLine();
			if (str.matches("\\d{1,2}")) {
				System.out.println("年龄是:" + Integer.parseInt(str));
				flag = false;
			} else {
				System.out.println("输入错误!重新输入:");
			}
		}
	}

}

Java IO高级应用(缓冲输入流)_第2张图片

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

范例3:进行文件读取

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class Demo {
	public static void main(String[] args) throws Exception {// 此处直接抛错
		BufferedReader buf = new BufferedReader(
				new FileReader("e:" + File.separator + "demo" + File.separator + "my.txt"));
		String str = null;
		while ((str = buf.readLine()) != null) {
			System.out.println(str);
		}
		buf.close();
	}

}

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