使用FileWriter和BufferedWriter向文本文件中写信息

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

/**
 * 使用FileWriter和BufferedWriter向文本文件中写信息
 * @author Administrator
 *
 */
public class BufferedWriterDemo {
	public static void main(String[] args) {
		//创建一个BufferedWriter
		Writer wr = null;
		BufferedWriter bw = null; 
		Reader rd = null;
		BufferedReader br = null;
		try {
			wr = new FileWriter("d:/hello.txt");
			bw = new BufferedWriter(wr);
			//写入信息
			bw.write("大家好!");
			bw.newLine();
			bw.write("我正在学习BufferedWriter.");
			bw.newLine();
			bw.write("请多多指教!"); 
			bw.flush();
			//读取文件中的信息
			rd = new FileReader("d:/hello.txt");
			br = new BufferedReader(rd);
			String line; //存储读取到的信息
			//读取信息
			while((line=br.readLine())!=null){
				System.out.println(line);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(bw!=null){
				try {
					bw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(wr!=null){
				try {
					wr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(rd!=null){
				try {
					rd.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

你可能感兴趣的:(I/O)