【问题标题】:Copy and rename file on different location在不同位置复制和重命名文件
【发布时间】:2011-07-20 06:39:12
【问题描述】:

我有一个文件 example.tar.gz,我需要将它复制到另一个名称不同的位置 例如 _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);

它不起作用。路径是正确的。它打印文件存在。有人可以帮帮我吗?

【问题讨论】:

  • close() 之前尝试flush() 您的流。
  • 在您的帖子中更正此代码:String from_path=new File("example.tar.gz");
  • @Mohamed,关闭之前不需要刷新
  • 你不需要带有 FileOutputStream 的 createNewFile,你也不应该使用 BufferedInputStream(),它并没有真正的帮助。只需使用大于 1k 的byte[] oBytes。最后但同样重要的是,FileChannel.transferTo 是复制Stuff 的最佳方式

标签: java


【解决方案1】:

为什么要重新发明轮子,就用FileUtils.copyFile(File srcFile, File destFile),它会为你处理很多场景

【讨论】:

  • 像梦一样工作
【解决方案2】:
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();
      }
    }
 }

【讨论】:

  • 使用 FileStreams 复制文件可能效率低下,看java.nio.channels.FileChannel.transferTo
【解决方案3】:

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

例如:Files.copy(sourcePath, targetPath)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2012-07-30
    • 2021-03-12
    • 2016-11-01
    • 2018-04-21
    • 1970-01-01
    • 2021-05-26
    相关资源
    最近更新 更多