Java复制文件的几种方法

1. 使用FileInputStream

public static void copy(File source, File destination) {
		try(FileInputStream fis = new FileInputStream(source);
				FileOutputStream fos = new FileOutputStream(destination)){
			byte[] bytes = new byte[2048];
			int read;
			while ((read = fis.read(bytes)) != -1) {
				fos.write(bytes, 0, read);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
}

2. 使用BufferedInputStream处理FileInputStream

public static void copyByBuffer(File source, File destination) {
		try(FileInputStream fis = new FileInputStream(source);
				FileOutputStream fos = new FileOutputStream(destination);
				BufferedInputStream bis = new BufferedInputStream(fis);
				BufferedOutputStream bos = new BufferedOutputStream(fos);){
			byte[] bytes = new byte[2048];
			int read;
			while ((read = bis.read(bytes)) != -1) {
				bos.write(bytes, 0, read);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
}

3.使用FileChannel

public static void copyByNio(File source, File destination) {
		try(FileChannel fromChannel = new FileInputStream(source).getChannel();
				FileChannel toChannel = new FileOutputStream(destination).getChannel();) {
			ByteBuffer buffer = ByteBuffer.allocate(2048);
			while (fromChannel.read(buffer) != -1) {//不用记录读取个数,buffer的position和limit字段会记录
				buffer.flip();//读模式
				toChannel.write(buffer);
				buffer.clear();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
}

4. 使用FileChannel的transfer方法

public static void FileCopyNio(File source, File destination) {
		try(FileChannel fromChannel = new FileInputStream(source).getChannel();
				FileChannel toChannel = new FileOutputStream(destination).getChannel();) {
			long count = fromChannel.size();
			fromChannel.transferTo(0, count, toChannel);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}	
}

5. 使用Apache Commons IO复制

Appache Commons IO 提供了一个FileUtils.copyFile(File from, File to)方法用于文件复制

public static void  copyFileByApacheCommonsIO(File source, File destination) throws IOException {
    FileUtils.copyFile(source, destination);
}

6. 使用Java7的Files类复制

注意参数是Path对象

public static void copyFileUsingJava7Files(File source, File destination) throws IOException {
    Files.copy(source.toPath(), destination.toPath());
}

性能测试……自己写

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值