java IO将一个文件复制到另一个文件

时间:2010-03-26 00:00:04

标签: java file file-io io java-io

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

6 个答案:

答案 0 :(得分:29)

不,没有内置方法可以做到这一点。最接近您想要完成的是来自transferFrom的{​​{1}}方法,如下所示:

FileOutputStream

不要忘记处理异常并关闭 FileChannel src = new FileInputStream(file1).getChannel(); FileChannel dest = new FileOutputStream(file2).getChannel(); dest.transferFrom(src, 0, src.size()); 块中的所有内容。

答案 1 :(得分:23)

如果你想要懒惰并且尽量少用代码 FileUtils.copyFile(src, dest) 来自Apache IOCommons

答案 2 :(得分: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();
    }
}

答案 3 :(得分:7)

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 :(得分:3)

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

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

答案 5 :(得分:1)

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