前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >实现文件拷贝

实现文件拷贝

作者头像
Mirror王宇阳
发布2020-11-12 11:13:30
1.3K0
发布2020-11-12 11:13:30
举报
文章被收录于专栏:Mirror的技术成长

方法一: 单字节逐一拷贝

代码语言:javascript
复制
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();
	}	
}
  • 遇到大容量的文件时,拷贝速度非常慢!!!

方法二:部分数据拷贝

代码语言:javascript
复制
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();
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-07-09 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 方法一: 单字节逐一拷贝
  • 方法二:部分数据拷贝
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档