IO流文件复制

package com.IO.demo;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.management.RuntimeErrorException;

//将C盘的一个文本文件复制到D盘
/**
 * 复制的原理
 *其实就是讲C盘下的文件数据存储到D盘的一个文件中。
 *
 *步骤:
 *1.在D盘创建一个文件,用于存储C盘文件中的数据。
 *2.定义读取流和C盘文件关联。
 *3.通过不断地读写完成数据存储。
 *4.关闭资源。
 */
public class Demo06 {
	public static void main(String[] args) throws IOException {
//		copy_1();
		copy_2();
	}
	
	//从C盘读一个字符,就往D盘写入一个字符。
	//方法1
	public static void copy_1() throws IOException{
		//创建目的地。
		FileWriter fw = new FileWriter("D:/demo03_copy.txt");
		
		//与已有文件关联
		FileReader fr = new FileReader("D:/demo03.txt");
		
		int ch = 0;
		
		while((ch=fr.read()) != -1){
			fw.write(ch);
		}
		fw.close();
		fr.close();
	}
	
	//方法2
	public static void copy_2() throws IOException{
		FileWriter fw = null;
		FileReader fr = null;
		try {
			fw = new FileWriter("D:/demo03_copy.txt");
			fr = new FileReader("D:/demo03.txt");
			
			char[] buf = new char[2];
			int len = 0;
			while((len = fr.read(buf)) != -1){ //达到流的末尾则返回-1
				System.out.println(len);
//				fw.write(buf);
				fw.write(buf,0,len);//从第下标0位开始往buf数组里面写入len个数
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException("读写失败");
		}finally{
			if(fr != null){
				try{
					fr.close();
				}catch(IOException e){
					throw new RuntimeException("fr关闭失败");
				}
			}
			if(fw != null){
				try{
					fw.close();
				}catch(IOException e){
					throw new RuntimeException("fw关闭失败");
				}
			}
		}
	}
	
}

你可能感兴趣的:(IO文件复制)