文件拷贝

在Java中,通过输入输出流实现一个文件的拷贝:

以.txt文件为例:

//文件拷贝;
class CopyFile {
	private CopyFile() {	
	}
	//判断要拷贝的源路径是否存在
	public static boolean isfileExists(String path) {
		return new File(path).exists();
	}
	//判断目标地址的父路径是否存在,不存在则创建
	public static void CreateParentDir(String path) {
		File file = new File(path);
		if(!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
		}
	}
	//是否拷贝成功
	public static boolean isCopyFile(String sourcePath,String destPath) throws IOException {
		File file1 = new File(sourcePath);
		File file2 = new File(destPath);
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;
		try {
			fileInputStream = new FileInputStream(file1);
			fileOutputStream = new FileOutputStream(file2);
			CopyFileHandle(fileInputStream,fileOutputStream);//完成具体的拷贝处理
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
			fileInputStream.close();
			fileOutputStream.close();
			}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return true;
	}
	//具体的拷贝操作
	public static void CopyFileHandle(InputStream fileInputStream, OutputStream outputStream) throws IOException {
		long start = System.currentTimeMillis();//开始计时
		//开辟缓冲区一次性读入多个内容
		byte[] data = new byte[1024];	
		while(fileInputStream.read(data) != -1) {//返回-1表示读取完毕
			 outputStream.write(data);
		}
		long end = System.currentTimeMillis();//结束计时
		System.out.println("拷贝所花时间:"+(end-start));
	}	
}
public class Main {
	public static void main(String[] args) throws IOException {
		String sourcePath = "C:\\Users\\CGX~LL\\Desktop\\singer.txt";//源路径
		String destPath = "C:\\Users\\CGX~LL\\Desktop\\singer2.txt";//目标路径
		if(CopyFile.isfileExists(sourcePath)) {
			CopyFile.CreateParentDir(destPath);
			System.out.println(CopyFile.isCopyFile(sourcePath,destPath)?"文件拷贝成功":"文件拷贝失败");
		}else {
			System.out.println("源文件不存在,无法拷贝");
		}
	}
}

创建了1KB的缓存空间,以提高效率;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值