在不同位置复制和重命名文件

时间:2011-03-22 07:41:50

标签: java

我有一个文件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);

但它不起作用。路径还可以。它打印存在的文件。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:30)

为什么重新发明轮子,只需使用FileUtils.copyFile(File srcFile, File destFile),这将为您处理许多场景

答案 1 :(得分:7)

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

或只是这个

致Josh的信用 - 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

更改为transferTo
 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();
      }
    }
 }

答案 2 :(得分:1)

软件包Files中有java.nio.file类。您可以使用copy方法。

示例:Files.copy(sourcePath, targetPath)

使用文件的新名称创建targetPath对象(它是Path的实例)。