欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java基础回顾之 流(BufferedReader/BufferedWriter )字符缓冲流, 默认有8192个字符的缓冲区

程序员文章站 2024-03-06 16:17:50
...

java基础回顾之 流(BufferedReader/BufferedWriter )字符缓冲流, 默认有8192个字符的缓冲区

package com.bjpowernode.demo03;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilterWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;

/**
 * BufferedReader/BufferedWriter
 * 	字符缓冲流, 默认有8192个字符的缓冲区
 * @author Administrator
 *
 */
public class Test04 {

	public static void main(String[] args) throws IOException {
//		readData(); 		//使用字符缓冲流读取文件内容
		
//		readDataFromKeyboard(); 	//有人也使用字符缓冲流从键盘上读取数据
		
		writeData();
		
	}

	private static void writeData() throws IOException {
		Writer out = new FileWriter("d:/out.txt");
		BufferedWriter bWriter = new BufferedWriter(out);
		
		bWriter.write("一次写一行");
		bWriter.newLine(); 			//换行 
		bWriter.write("这是第二行");
		
		bWriter.flush();
		bWriter.close();
	}

	private static void readDataFromKeyboard() throws IOException {
		//把键盘字节流转换为字符流
		Reader in  = new InputStreamReader(System.in);
		//对字符流进行缓冲
		BufferedReader br = new BufferedReader(in);
		
		FileWriter fw = new FileWriter("d:/key.txt");
		
		String line = br.readLine();
		while( line.length() > 0 ){
//		while( line != null  ){
			System.out.println( line);
			fw.write(line);
			fw.write("\r\n");
			line = br.readLine();
		}
		
		br.close();
		fw.close();
	}

	private static void readData() throws IOException {
		//读取d:/test01.java文件, 该文件采用UTF-8编码
//		Reader in = new FileReader("d:/test01.java");
		//读取d:/out.txt文件,该文件采用GBK编码, 当前环境使用UTF-8
		Reader in = new InputStreamReader(new FileInputStream("d:/out.txt"), "GBK");
	
		BufferedReader br = new BufferedReader(in);
		
		//一次读取一行, 读到文件末尾返回null
		String line = br.readLine();
		while( line != null ){
			System.out.println( line );
			line = br.readLine();
		}
		
		br.close();
	}

}

相关标签: java web开发