Java 文件合并功能 用FileChannel和Stream拷贝合并追加写文件

该博客介绍了如何在Java中使用FileChannel和Stream来合并多个文件。通过创建FileCombineFetch类,它接受目标文件名和临时文件集合,然后逐个读取临时文件并将其内容追加到目标文件中,最后删除所有临时文件。FileCombineManager类负责检查临时文件是否准备就绪,并启动合并线程。
摘要由CSDN通过智能技术生成

用filechannel更方便一些


/**  
Copy files, using two techniques, FileChannels and streams. 
Using FileChannels is usually faster than using streams. 
*/ 
public final class CopyFiles { 
  
 /* Change these settings before running this class. */ 
  
 /** The file to be copied. */ 
 public static final String INPUT_FILE = "C:\\TEMP\\cottage.jpg"; 
  
 /** 
  The name of the copy to be created by this class.   
  If this file doesn't exist, it will be created, along with any  
  needed parent directories.   
 */ 
 public static final String COPY_FILE_TO = "C:\\TEMP10\\cottage_2.jpg"; 
  
 /** Run the example. */ 
 public static void main(String... aArgs) throws IOException{ 
   File source = new File(INPUT_FILE); 
   File target = new File(COPY_FILE_TO); 
   CopyFiles test = new CopyFiles(); 
   test.copyWithChannels(source, target, false); 
   //test.copyWithStreams(source, target, false); 
   log("Done."); 
 } 
 
 /** This may fail for VERY large files. */ 
 private void copyWithChannels(File aSourceFile, File aTargetFile, boolean aAppend) { 
   log("Copying files with channels."); 
   ensureTargetDirectoryExists(aTargetFile.getParentFile()); 
   FileChannel inChannel = null; 
   FileChannel outChannel = null; 
   FileInputStream inStream = null; 
   FileOutputStream outStream = null; 
   try{ 
     try { 
       inStream = new FileInputStream(aSourceFile); 
       inChannel = inStream.getChannel(); 
       outStream = new  FileOutputStream(aTargetFile, aAppend);         
       outChannel = outStream.getChannel(); 
       long bytesTransferred = 0; 
       //defensive loop - there's usually only a single iteration : 
       while(bytesTransferred < inChannel.size()){ 
         bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel); 
       } 
     } 
     finally { 
       //being defensive about closing all channels and streams  
       if (inChannel != null) inChannel.close(); 
       if (outChannel != null) outChannel.close(); 
       if (inStream != null) inStream.close(); 
       if (outStream != null) outStream.close(); 
     } 
   } 
   catch (FileNotFoundException ex){ 
     log("File not found: " + ex); 
   } 
   catch (IOException ex){ 
     log(ex); 
   } 
 } 
  
 private void copyWithStreams(File aSourceFile, File aTargetFile, boolea
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值