Java-将文件复制到新文件或现有文件

5 java file

我想写一个函数副本(File f1,File f2)f1总是一个文件.f2是文件或目录.

如果f2是一个目录,我想将f1复制到这个目录(文件名应该保持不变).

如果f2是一个文件,我想将f1的内容复制到文件f2的末尾.

例如,如果F2有内容:

2222222222222

F1有内容

1111111111111

我复制(f1,f2)然后f2应该成为

2222222222222

1111111111111

谢谢!

Eli*_*jah 17

Apache Commons IO来救援!

扩展Allain的帖子:

  File f1 = new File(srFile);
  File f2 = new File(dtFile);

  InputStream in = new FileInputStream(f1);
  OutputStream out = new FileOutputStream(f2, true); // appending output stream

  try {
     IOUtils.copy(in, out);
  }
  finally {
      IOUtils.closeQuietly(in);
      IOUtils.closeQuietly(out);
  }
Run Code Online (Sandbox Code Playgroud)

使用Commons IO可以简化许多流grunt工作.


Jar*_*aus 5

使用Allain Lolande的答案中的代码并对其进行扩展,这应该解决您问题的两个部分:

File f1 = new File(srFile);
File f2 = new File(dtFile);

// Determine if a new file should be created in the target directory,
// or if this is an existing file that should be appended to.
boolean append;
if (f2.isDirectory()) {
    f2 = new File(f2, f1.getName());
    // Do not append to the file. Create it in the directory, 
    // or overwrite if it exists in that directory.
    // Change this logic to suite your requirements.
    append = false;
} else {
    // The target is (likely) a file. Attempt to append to it.
    append = true;
}

InputStream in = null;
OutputStream out = null;
try {
    in = new FileInputStream(f1);
    out = new FileOutputStream(f2, append);

    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
} finally {
    if (out != null) {
        out.close();
    }
    if (in != null) {
        in.close();
    }
}
Run Code Online (Sandbox Code Playgroud)


Mr.*_*ill 1

查看下面的链接。它是一个使用 NIO 将一个文件复制到另一个文件的源文件。

http://www.java2s.com/Code/Java/File-Input-Output/CopyafileusingNIO.htm