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

Dam*_*mir 9 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();
}
Run Code Online (Sandbox Code Playgroud)

哪里

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();
Run Code Online (Sandbox Code Playgroud)

然后

copyFile(source, destination);
Run Code Online (Sandbox Code Playgroud)

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

Jig*_*shi 32

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


Dea*_*mer 7

I would suggest Apache commons FileUtils or NIO (direct OS calls)
Run Code Online (Sandbox Code Playgroud)

或者就是这个

对Josh的信用 - 标准简洁 - 复制文件在java中


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

copyFile(source,destination);
Run Code Online (Sandbox Code Playgroud)

更新:

从@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();
      }
    }
 }
Run Code Online (Sandbox Code Playgroud)