2017-05-19 57 views
0

副本时我已经执行以下代码复制文件(二进制文件) 代码的java:使用NIO

private void copyFileWithChannels(File aSourceFile, File aTargetFile) { 
     log("Copying files with channels.");   
     FileChannel inChannel = null; 
     FileChannel outChannel = null; 
     FileInputStream inStream = null; 
     FileOutputStream outStream = null;  
     try { 
      inStream = new FileInputStream(aSourceFile); 
      inChannel = inStream.getChannel(); 
      outStream = new FileOutputStream(aTargetFile);   
      outChannel = outStream.getChannel(); 
      long bytesTransferred = 0; 
      while(bytesTransferred < inChannel.size()){ 
       bytesTransferred += inChannel.transferTo(0, inChannel.size(), outChannel); 
      } 
     } 
     catch(FileNotFoundException e){ 
      log.error("FileNotFoundException in copyFileWithChannels()",e); 
     } 
     catch (IOException e) { 
      log.error("IOException in copyFileWithChannels()",e);   
     } 
     catch (Exception e) { 
      log.error("Exception in copyFileWithChannels()",e); 
     } 
     finally { 
      try{ 
       if (inChannel != null) inChannel.close(); 
       if (outChannel != null) outChannel.close(); 
       if (inStream != null) inStream.close(); 
       if (outStream != null) outStream.close(); 
      }catch(Exception e){ 
       log.error("Exception in copyFileWithChannels() while closing the stream",e); 
      } 
     } 

    } 

我有一个zip文件测试代码损坏的ZIP文件中创建。当我验证文件时,我发现生成的文件已损坏(大小增加)。 源zip文件大约9GB。

回答

1

transferTo方法的第一个参数给出了从哪里传送的位置nsfer,而不是相对于流停止的地方,但相对于文件的开始。由于您将0放在那里,因此它始终会从文件的开始处传输。因此,该行需要在他的回答中提到

bytesTransferred += inChannel.transferTo(bytesTransferred , inChannel.size(), outChannel); 

mavarazy他不知道,如果你使用inChannel.size()时,需要一个循环,因为预期的是,如果你提供全尺寸会复制整个文件。但是,如果输出通道的缓冲区空间不足,实际传输可能会少于所请求的字节数。所以你需要在他的第二个代码片段中的循环。

+0

我已更正我的答案,谢谢 – mavarazy