This example will show how to copy a file or directory from one location to another using java, guava, apache commons and spring framework. There are many use cases where you need to copy a file from one directory to another. Lets say you are writing an application to upload EAR files that need to be deployed to multiple application servers. After the upload from your browser to a temporary location you will want to copy the file to multiple directories on your network.
In the initial set up below we created a constant for the SOURCE file we want to copy and the DEST we want to copy it to. Be sure when selecting your preferred approach that you check with the associated java docs as each approach has varying behavior
Straight up Java
Using FileInputStream and FileOutputStream we will move a file from a source location to a destination location. A FileInputStream purpose is for reading streams of raw bytes such as image data and obtains the bytes from a file or file system. In conjunction with FileOutputStream we will loop over the input stream and write the bytes back to the output stream.
Java 7 File I/O
Java 7 NIO introduced a simplified way to copy a file Files utility class. We will specify a Path for the source and destination and then pass them as the first and second parameter into the Files.copy method. The third parameter is a CopyOption giving direction on what behavior to take when making the move. In the snippet below we specified
StandardCopyOption.REPLACE_EXISTING as we wanted to replace a file if it already existed. Other options include COPY_ATTRIBUTES and ATOMIC_MOVE.
Guava Files copy will copy all of the bytes from one file to another and in the event that the TO file exists it will be over written with the from contents.
There are a couple of different ways to copy a file with apache commons both result in copying a file. The first uses FileUtils which copies a file to a new location which copies the contents of the source file to the destination file. If the directory holding the destination file doesn't exist it will be created.
The second is IOUtils which copied the bytes from an InputStream to an OutputStream using an underlying BufferedInputStream. A note in the java doc states that if you are dealing with large streams you should look to use the copyLarge(InputStream, OutputStream) method.
Spring framework or spring.io utility class with dealing with files is FileCopyUtils which is primarily used within the framework. The FileCopyUtils.copy like the methods above copies the contents of the given input File to the given output File.