IO之复制文件的四种方式

1. 使用FileStreams复制

这是最经典的方式将一个文件的内容复制到另一个文件中。 使用FileInputStream读取文件A的字节,使用FileOutputStream写入到文件B。 这是第一个方法的代码:

 1 private static void copyFileUsingFileStreams(File source, File dest)
 2         throws IOException {    
 3     InputStream input = null;    
 4     OutputStream output = null;    
 5     try {
 6            input = new FileInputStream(source);
 7            output = new FileOutputStream(dest);        
 8            byte[] buf = new byte[1024];        
 9            int bytesRead;        
10            while ((bytesRead = input.read(buf)) > 0) {
11                output.write(buf, 0, bytesRead);
12            }
13     } finally {
14         input.close();
15         output.close();
16     }
17 

2. 使用FileChannel复制

 1 private static void copyFileUsingFileChannels(File source, File dest) throws IOException {    
 2         FileChannel inputChannel = null;    
 3         FileChannel outputChannel = null;    
 4     try {
 5         inputChannel = new FileInputStream(source).getChannel();
 6         outputChannel = new FileOutputStream(dest).getChannel();
 7         outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
 8     } finally {
 9         inputChannel.close();
10         outputChannel.close();
11     }
12 }

 

3. 使用Commons IO复制

 private static void copyFileUsingApacheCommonsIO(File source, File dest)
         throws IOException {
     FileUtils.copyFile(source, dest);
 }

 

4. 使用Java7的Files类复制

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

 

转载于:https://www.cnblogs.com/tanyang/p/11511559.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值