It has always bothered me that the only way to copy a file in Java involves opening streams, declaring a buffer, reading in one file, looping through it, and writing it out to the other steam. The web is littered with similar, yet still slightly different implementations of this type of solution.
Is there a better way that stays within the bounds of the Java language (meaning does not involve exec-ing OS specific commands)? Perhaps in some reliable open source utility package, that would at least obscure this underlying implementation and provide a one line solution?
I would avoid the use of a mega api like apache commons. This is a simplistic operation and its built into the JDK in the new NIO package. It was kind of already linked to in a previous answer, but the key method in the NIO api are the new functions "transferTo" and "transferFrom".
http://java.sun.com/javase/6/docs/api/java/nio/channels/FileChannel.html#transferTo(long,%20long,%20java.nio.channels.WritableByteChannel)
One of the linked articles shows a great way on how to integrate this function into your code, using the transferFrom:
Learning NIO can be a little tricky, so you might want to just trust in this mechanic before going off and trying to learn NIO overnight. From personal experience it can be a very hard thing to learn if you don't have the experience and were introduced to IO via the java.io streams.
The utility class
Copying a directory or file
Moving a directory or file
Copying a directory or file recursively
Google's Guava library also has a copy method:
Warning: If
to
represents an existing file, that file will be overwritten with the contents offrom
. Ifto
andfrom
refer to the same file, the contents of that file will be deleted.Parameters:
from
- the source fileto
- the destination fileThrows:
IOException
- if an I/O error occursIllegalArgumentException
- iffrom.equals(to)
Here is three ways that you can easily copy files with single line of code!
Java7:
java.nio.file.Files#copy
Appache Commons IO:
FileUtils#copyFile
Guava :
Files#copy
In Java 7 it is easy...