Java I/O Reader and Writer

public class FileCopy {

	/**
	 * 1、在D盘创建一个文件,用于存储C盘文件中的数据。
	 * 2、定义读取流和C盘文件关联
	 * 3、通过不断的读写完成数据存储。
	 * 4,关闭资源
	 */
	public static void main(String[] args) {
		FileWriter fw = null;
		FileReader fr = null;
		try {
			fw = new FileWriter("D:/java.txt",true);
			fw.write("abcde");
			fw.flush();
			fr = new FileReader("D:/java.txt");
			char[] chs = new char[1024];
			int len = 0;
			fw = new FileWriter("D:/java3.txt");
			while((len=fr.read(chs))!=-1){
				fw.write(chs, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("读写失败");
		} finally{
			if(fw!=null)
				try {
					fw.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if(fr!=null)
				try {
					fr.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
	}

}
package com.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedCopy {
   //通过缓冲区复制一个java文件
	public static void main(String[] args) {
		BufferedReader br = null;
		BufferedWriter bw = null;
		try {
			br = new BufferedReader(new FileReader("d:/FileCopy.java"));
			bw = new BufferedWriter(new FileWriter("d:/FileCopy_Copy.java"));
			String n = null;
			while((n=br.readLine())!=null){
				//readLine()不会返回终止符(回车符),所以每写一行要换行一次加入newLine()
				bw.write(n);
				bw.newLine();
				bw.flush();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(br!=null)
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if(bw!=null){
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}

}

  

posted @ 2013-09-06 00:02  微风夜明  阅读(224)  评论(0)    收藏  举报