I have two Java.io.File objects file1 and file2. I want to copy the contents from file1 to file2. Is there an standard way to do this without me having to create a method that reads file1 and write to file2
+2
A:
No. Every long-time Java programmer has their own utility belt that includes such a method. Here's mine.
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();
}
}
Jonathan Feinberg
2010-03-26 00:03:41
No copyFileToInputStream?
Software Monkey
2010-03-26 00:35:21
This was an *excerpt*. :)
Jonathan Feinberg
2010-03-26 00:56:01
+5
A:
No, there is no built-in method to do that. The closest to what you want to accomplish is the transferFrom
method from FileOutputStream
, like so:
FileChannel src = new FileInputStream(file1).getChannel();
FileChannel dest = new FileOutputStream(file2).getChannel();
dest.transferFrom(src, 0, src.size());
And don't forget to handle exceptions and close everything in a finally
block.
JG
2010-03-26 00:08:33
A more complete (and correct) version of this answer is available here: http://stackoverflow.com/questions/106770/standard-concise-way-to-copy-a-file-in-java/115086#115086. Thanks to http://stackoverflow.com/users/92937/twentymiles for schooling all of us.
vkraemer
2010-03-26 03:20:19
+4
A:
If you want to be lazy and get away with writing minimal code use
FileUtils.copyFile(src, dest)
from Apache IOCommons
Maddy
2010-03-26 02:43:42