2011-03-22 83 views
8

我有一个文件example.tar.gz,我需要复制到另一个名称不同的位置 example_test.tar.gz。我试着用在不同位置复制和重命名文件

private void copyFile(File srcFile, File destFile) throws IOException 
    { 
      InputStream oInStream = new FileInputStream(srcFile); 
      OutputStream oOutStream = new FileOutputStream(destFile); 

      // Transfer bytes from in to out 
      byte[] oBytes = new byte[1024]; 
      int nLength; 
      BufferedInputStream oBuffInputStream = 
          new BufferedInputStream(oInStream); 
      while ((nLength = oBuffInputStream.read(oBytes)) > 0) 
      { 
       oOutStream.write(oBytes, 0, nLength); 
      } 
      oInStream.close(); 
      oOutStream.close(); 
    } 
} 

其中

String from_path=new File("example.tar.gz"); 
File source=new File(from_path); 

File destination=new File("/temp/example_test.tar.gz"); 
      if(!destination.exists()) 
       destination.createNewFile(); 

然后

copyFile(source, destination); 

,但它不工作。路径没问题。它打印存在的文件。任何人都可以帮忙吗?

+0

尝试'的flush()'你流之前'接近()'荷兰国际集团将其改为的transferTo。 – 2011-03-22 07:45:01

+0

在你的文章中更正这段代码:'''''from_path = new File(“example.tar.gz”);' – 2011-03-22 07:52:10

+2

@Mohamed,关闭之前不需要刷新 – bestsss 2011-03-22 07:53:49

回答

6
I would suggest Apache commons FileUtils or NIO (direct OS calls) 

或就在这个

现金约什 - standard-concise-way-to-copy-a-file-in-java


File source=new File("example.tar.gz"); 
File destination=new File("/temp/example_test.tar.gz"); 

copyFile(source,destination); 

更新:

从@bestss

public static void copyFile(File sourceFile, File destFile) throws IOException { 
    if(!destFile.exists()) { 
     destFile.createNewFile(); 
    } 

    FileChannel source = null; 
    FileChannel destination = null; 
    try { 
     source = new RandomAccessFile(sourceFile,"rw").getChannel(); 
     destination = new RandomAccessFile(destFile,"rw").getChannel(); 

     long position = 0; 
     long count = source.size(); 

     source.transferTo(position, count, destination); 
    } 
    finally { 
     if(source != null) { 
     source.close(); 
     } 
     if(destination != null) { 
     destination.close(); 
     } 
    } 
} 
+0

使用FileStreams复制文件可能效率低下,查看'java.nio.channels.FileChannel.transferTo' – bestsss 2011-03-22 07:59:57

相关问题