Java IO 复制一个文件到另一个文件

20
我有两个Java.io.File对象file1和file2。我想将file1的内容复制到file2中。是否有一种标准的方法可以做到这一点,而无需创建一个读取file1并写入file2的方法?

4
请参考https://dev59.com/8nVD5IYBdhLWcg3wDHDm,这篇文章提供了Java中拷贝文件的标准简洁方法。 - TwentyMiles
对于文件和字符串,您最好使用Utils类,如FileUtils和StringUtils。它们具有广泛的预定义方法来操作文件和字符串。它们包含在Apache Common包中,您可以将其添加到您的pom.xml中。 - Mahmoud Turki
6个回答

32
不,没有内置方法可以做到这一点。最接近你想要实现的是使用FileOutputStream中的transferFrom方法,像下面这样:
  FileChannel src = new FileInputStream(file1).getChannel();
  FileChannel dest = new FileOutputStream(file2).getChannel();
  dest.transferFrom(src, 0, src.size());

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


这个问题的一个更完整(并且正确)的版本可以在这里找到:https://dev59.com/8nVD5IYBdhLWcg3wDHDm#115086。感谢http://stackoverflow.com/users/92937/twentymiles给我们上了一堂课。 - vkraemer
对于文件和字符串,您最好使用Utils类,如FileUtils和StringUtils。它们具有广泛的预定义方法来操作文件和字符串。它们包含在Apache Common包中,您可以将其添加到您的pom.xml中。 - Mahmoud Turki

29
如果你想偷懒并且只写最少的代码,可以使用:
FileUtils.copyFile(src, dest)

来自 Apache IOCommons


3
我热衷于极简代码。不确定使用实用程序包为何会被称作“懒惰”。我喜欢 StringUtils。 - Jeremy Goodell

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();
    }
}

9
自从Java 7开始,你可以使用Java标准库中的Files.copy()方法。
你可以创建一个包装方法:
public static void copy(String sourcePath, String destinationPath) throws IOException {
    Files.copy(Paths.get(sourcePath), new FileOutputStream(destinationPath));
}

可以按以下方式使用:
copy("source.txt", "dest.txt");

4

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

OutputStream os = new FileOutputStream(targetFile);
Files.copy(Paths.get(sourceFile), os);
os.close();

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接