我有两个Java.io.File对象file1和file2。我想将file1的内容复制到file2中。是否有一种标准的方法可以做到这一点,而无需创建一个读取file1并写入file2的方法?
FileOutputStream
中的transferFrom
方法,像下面这样: FileChannel src = new FileInputStream(file1).getChannel();
FileChannel dest = new FileOutputStream(file2).getChannel();
dest.transferFrom(src, 0, src.size());
不要忘记在 finally
块中处理异常并关闭所有内容。
FileUtils.copyFile(src, dest)
来自 Apache IOCommons
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();
}
}
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");
在Java 7中,您可以使用Files.copy()
方法,非常重要的是:创建新文件后不要忘记关闭OutputStream。
OutputStream os = new FileOutputStream(targetFile);
Files.copy(Paths.get(sourceFile), os);
os.close();