实现文件拷贝

方法一: 单字节逐一拷贝

public class TestDemo {
	public static void main(String [] args) throws IOException {
		// 将文件的源和目的位置初始化到file数组中
		String [] str = {"F:\\demo\\demo.txt","F:\\demo\\Demo1.txt"};
		if (str.length != 2) {
			System.out.println("命令执行错误");
			System.exit(1);// 退出程序
		}
		File inFile = new File(str[0]); // 源文件
		if(!inFile.exists()) { //源文件是否存在
			System.out.println("源文件不存在");
			System.exit(1);
		}
		File outFile = new File(str[1]);
		if (!outFile.getParentFile().exists()) { // 目的是否存在
			outFile.getParentFile().mkdirs(); //创建目录以及文件
		}
		InputStream input = new FileInputStream(inFile);
		OutputStream output = new FileOutputStream(outFile);
		// 完成两个文件的实例对象
		int temp = 0 ; //保存读取的内容
		while ((temp = input.read()) != -1) { // 每次读取单个字节,输出到目标文件中
			output.write(temp);
		}
		input.close();
		output.close();
	}	
}
  • 遇到大容量的文件时,拷贝速度非常慢!!!

方法二:部分数据拷贝

public class TestDemo {
	public static void main(String [] args) throws IOException {
		// 将文件的源和目的位置初始化到file数组中
		String [] str = {"F:\\demo\\demo.txt","F:\\demo\\Demo1.txt"};
		if (str.length != 2) {
			System.out.println("命令执行错误");
			System.exit(1);// 退出程序
		}
		File inFile = new File(str[0]); // 源文件
		if(!inFile.exists()) { //源文件是否存在
			System.out.println("源文件不存在");
			System.exit(1);
		}
		File outFile = new File(str[1]);
		if (!outFile.getParentFile().exists()) { // 目的是否存在
			outFile.getParentFile().mkdirs(); //创建目录以及文件
		}
		InputStream input = new FileInputStream(inFile);
		OutputStream output = new FileOutputStream(outFile);
		// 完成两个文件的实例对象
		int temp = 0 ; //保存读取的内容
		byte [] data = new byte[1024]; // 每次读取1024字节
		while ((temp = input.read(data)) != -1) { // 每次读取单个字节,输出到目标文件中
			output.write(data,0,temp);
		}
		input.close();
		output.close();
	}
}
posted @ 2019-07-09 20:46  Mirror王宇阳  阅读(176)  评论(0编辑  收藏  举报