9.Java基础:常见IO流----->字符流中的缓冲流:BufferedReader 、BufferedWriter

BufferedReader 

1.它是一个可以提高效率的字符输入流。

2.是一个自带缓冲区的流,它可以包装一个字符流,提高其读取效率。
3,.当BufferedReader创建时,如果没有指定缓冲区大小,它底层默认的char[] 大小是1024*8

1.构造:

new BufferedReader(Reader r);

new BufferedReader(Reader r ,int size);

2.读取

read()

//要求从键盘接收多个字符
public class BufferedReaderDemo {
	public static void main(String[] args) throws IOException {
		fun1();
	}

	private static void fun1() throws IOException {
		char[] ch = new char[1024];
		
		//从键盘读取字节
		InputStream is = System.in;
		
		//读取字符,对is包装
		InputStreamReader isr = new InputStreamReader(is);
	
		//一次读多个
		int len = isr.read(ch);
		System.out.println(new String(ch, 0, len));
	}
}

read(char[] ch)

//要求从键盘接收多个字符
public class BufferedReaderDemo {
	public static void main(String[] args) throws IOException {
		bufferedReader(); //缓冲流输入流
	}

	//把数据存储到一个数组,叫缓冲存储下数据
	private static void bufferedReader() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String msg = br.readLine();
		System.out.println(msg);
	}
}

readLine();---->重点
public String readLine();
一次读取一行信息。如果遇到\r \n就认为一行结束。

如果返回null,代表读取末尾。

public class BufferedReaderDemo {
	public static void main(String[] args) throws IOException {
		fun2(); //读取文件
	}
	
	private static void fun2() throws IOException {
		//读取文本信息
		BufferedReader br = new BufferedReader(new FileReader("e:/a.txt"));
		while(true) {
			String msg = br.readLine(); //一次读取一行信息,不包括换行符
			if (msg == null) {
				break;
			}
			
			System.out.println(msg);
		}
	}
}

BufferedWriter

newLine();写入一个换行符.

//注意:对于这些包装流来说,当执行包装流的close方法时,会将其包装的流也关闭。	
public class BufferedWriterDemo {
	public static void main(String[] args) throws IOException {
		writer();
	}

	//将文件复制--->逆序
	public static void writer() throws IOException {
		//创建集合,保存每行信息
		List msg = new ArrayList();
		
		//1.创建读取文件信息流
		BufferedReader br = new BufferedReader(new FileReader("e:/a.txt"));
		
		//2.向b.txt文件写入流
		BufferedWriter bw = new BufferedWriter(new FileWriter("e:/b.txt"));
	
		String line = null;
		while ((line = br.readLine()) != null) {
			msg.add(line);
		}
		Collections.reverse(msg); //反转
		
		for (String s:msg) {
			bw.write(s);
			bw.newLine();
			bw.flush();
		}
		
		bw.close();
		br.close();
	}
}

你可能感兴趣的:(Java基础)