Java has the features of the copying the directory and it's contents. This example shows how to copy the directory and files into a new directory.
In this program, you will see how contains of a directory or a file is copied from the specified source directory (subdirectories and files) to specified destination directory. If you specify the unknown source directory which does not exist then the program gives the output message like : File or directory does not exist. otherwise read the source directory name and create the OutputStream instance for the destination directory while if you specify the unknown destination directory name then the program creates new directory with that name for the destination directory where the contents of the source directory have to be copied.
In this program, there are two methods have been used to complete the program. These methods are explained ahead :
copyDirectory (File srcPath, File dstPath):
The copyDirectory() method is used to copy contents from the specified source directory to the specified destination directory. This method takes two File type arguments passed by the calling method in the main method and check whether the specified directory is a directory exactly or not. If the specified name is in the exact directory format and that exists then the method generates the list of all the sub directories and file inside the source directory using the list() method and copy one by one to the destination directory otherwise the specified name is copies (treated) as a file name directly.
And another method is the main method in which the program read the source and destination directory or file name.
Here is the code of the program :
Output of the Program:
Enter the source directory or file name :test
Enter the destination directory or file name :dir1
Recommend the tutorial