20

我有两个 Java.io.File 对象 file1 和 file2。我想将文件1的内容复制到文件2。有没有一种标准方法可以做到这一点,而我不必创建一个读取 file1 并写入 file2 的方法

4

6 回答 6

32

不,没有内置的方法可以做到这一点。最接近您想要完成的是transferFromfrom 的方法FileOutputStream,如下所示:

  FileChannel src = new FileInputStream(file1).getChannel();
  FileChannel dest = new FileOutputStream(file2).getChannel();
  dest.transferFrom(src, 0, src.size());

并且不要忘记处理异常并在一个finally块中关闭所有内容。

于 2010-03-26T00:08:33.547 回答
28

如果您想偷懒并摆脱编写最少的代码,请使用

FileUtils.copyFile(src, dest)

来自 Apache IOCommons

于 2010-03-26T02:43:42.307 回答
9

不,每个长期的 Java 程序员都有自己的实用工具带,其中包含这种方法。这是我的。

public static void copyFileToFile(final File src, final File dest) throws IOException
{
    copyInputStreamToFile(new FileInputStream(src), dest);
    dest.setLastModified(src.lastModified());
}

public static void copyInputStreamToFile(final InputStream in, final File dest)
        throws IOException
{
    copyInputStreamToOutputStream(in, new FileOutputStream(dest));
}


public static void copyInputStreamToOutputStream(final InputStream in,
        final OutputStream out) throws IOException
{
    try
    {
        try
        {
            final byte[] buffer = new byte[1024];
            int n;
            while ((n = in.read(buffer)) != -1)
                out.write(buffer, 0, n);
        }
        finally
        {
            out.close();
        }
    }
    finally
    {
        in.close();
    }
}
于 2010-03-26T00:03:41.407 回答
9

Java 7开始,您可以Files.copy()从 Java 的标准库中使用。

您可以创建一个包装方法:

public static void copy(String sourcePath, String destinationPath) throws IOException {
    Files.copy(Paths.get(sourcePath), new FileOutputStream(destinationPath));
}

可以通过以下方式使用:

copy("source.txt", "dest.txt");
于 2014-04-06T20:29:46.423 回答
4

Java 7中您可以使用Files.copy()并且非常重要的是:不要忘记在创建新文件后关闭 OutputStream

OutputStream os = new FileOutputStream(targetFile);
Files.copy(Paths.get(sourceFile), os);
os.close();
于 2017-10-30T14:34:58.970 回答
1

或者使用Google 的 Guava 库中的Files.copy(file1,file2)

于 2012-03-23T20:29:57.377 回答