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

Aly*_*Aly 18 java io file-io file java-io

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

Joã*_*lva 30

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

  FileChannel src = new FileInputStream(file1).getChannel();
  FileChannel dest = new FileOutputStream(file2).getChannel();
  dest.transferFrom(src, 0, src.size());
Run Code Online (Sandbox Code Playgroud)

并且不要忘记处理异常并关闭finally块中的所有内容.


Mad*_*ddy 24

如果你想要懒惰并且__CODE__ 从Apache IOCommons 编写最少的代码使用

  • 我是最小代码的粉丝.不知道为什么使用实用程序包是"懒惰"的.我喜欢StringUtils. (2认同)

Jon*_*erg 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();
    }
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ski 7

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

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

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

可以通过以下方式使用:

copy("source.txt", "dest.txt");
Run Code Online (Sandbox Code Playgroud)