Java IO – File Copying, Moving and Deleting

File and directory Copying

Copying using

To copy a file, read the data from the file using an inputstream and write to another file using an outputstream. But there are better methods for copying, so we will not spend any time on this. However, if you are interested in using this method then read up the tutorial on file reading and writing.

copying using java.nio.file.Files

Use the copy method to copy contents to the outputstream. The copy works by copying contents from source, putting it in a buffer and then writing the buffer to the outputstream. There are various variants of this method. we could use path for both source and target or a path for target and an inputstream for source. This later method can be used to read files from the web

Data can be transferred using the transferTo(..) and transferFrom(..) methods of the java.nio.channels.FileChannel class. These methods use the underlying optimization of the file system and therefore in certain cases data transfer can be fast, especially for large files. However, note that the implementation is file system specific and it would be false to claim that this method is always faster then the above methods. In the example below we copy tempFile1 to tempFile2

Another way to copy file is to use and

To copy a directory use the directory copy method of The method below copies all contents from directory A to directory B. The directory B is created if not present. The copy method preserves file dates. The directory is of type

File and Directory Moving

Move a file. The command below moves FileA to FileB in the same directory. it can be thought of as a rename. The REPLACE_EXISTING option replaces FileB if already present. If its a symbolic link then the link is copied and not the target.

The move method can also be used to move the contents of a directory. If the target is a non empty directory than replace would not work and the method will fail. The ‘Atomic’ options ensures that all files are moved or none. The move method does not work if it involves moving files across file stores.

Move methods exist in apache commons io. There are other variants of this method as well, such as moveDirectory(..),moveDirectoryToDirectory(..),moveFileToDirectory(..),moveToDirectory(..)

Deleting file or Directory

Delete a file or directory using The directory needs to be empty.

Delete a file or directory using java.nio.file.Files. The directory needs to be empty. if the Path is a symbolic link, then the link is deleted and not the target that it represents.

Apache Commons IO has methods to delete a directory recursively. The method deleteQuietly(..) deletes a file or a directory without throwing an exception. The directory is deleted recursively.

Renaming file or directory

To rename a file or a directory use the renameTo method of or use any of the move methods described above.

Leave a Comment