天天看点

拷贝文本文件

拷贝文本文件

package com.io;

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

/**
 * 将c盘一个文本文件复制到D盘
 * @author 小明
 *1、在D盘创建一个文件.用于存储c盘文件中的数据
 *2、定义读取流
 *3、
 *4、关闭资源
 */
public class CopyDemo {
public static void main(String[] args) throws IOException {
	copy_1();
}

public static void copy_2(){
	FileWriter fw =null;
	FileReader fr =null;
	try {
		 fw = new FileWriter("C:\\Users\\小明\\Desktop\\peoplexxx.txt");
		 fr = new FileReader("C:\\Users\\小明\\Desktop\\people2.txt");
      char[] buf = new char[1024];
		int len =0;
		while((len=fr.read(buf))!=-1){
			fw.write(buf, 0, len);
		}
	} catch (Exception e) {
		
	}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();
			}
		}
		
	}
}

//从c盘读取一个字符就往D盘写一个字符
public static void copy_1() throws IOException{
	//创建目的文件
	FileWriter fw = new FileWriter("C:\\Users\\小明\\Desktop\\peoplexxx.txt");

	//与已有文件关联
	FileReader fr = new FileReader("C:\\Users\\小明\\Desktop\\people2.txt");

   int ch =0;
   while((ch=fr.read())!=-1){
	   fw.write(ch);
   }
   fw.close();
   fr.close();
}
}
           

继续阅读