Code to copy file1.txt from examples folder and make a new copy in the same folder under the name filecopy.txt is below First time we run the program it will create the copy as filecopy.txt does not exist Second time we run it will throw exception saying filecopy.txt already exists. So to overwrite the existing file we can do the following i.e pass a third parameter to overloaded copy method to replace existing file
// Files.copy(sourceFile,copyFile, StandardCopyOption.REPLACE_EXISTING);
Complete code
try{
Path sourceFile = FileSystems.getDefault().getPath("Examples","file1.txt");
Path copyFile = FileSystems.getDefault().getPath("Examples","filecopy.txt");
Files.copy(sourceFile,copyFile);
// Files.copy(sourceFile,copyFile, StandardCopyOption.REPLACE_EXISTING);
//We can even copy an entire Dir as follows. Below we can make a copy of Dir1 and name it as Dir4
//Please note that the below code will only copy the folder Dir1 and not any of the files in Dir1
sourceFile = FileSystems.getDefault().getPath("Examples","Dir1");
copyFile = FileSystems.getDefault().getPath("Examples","Dir4");
// Files.copy(sourceFile,copyFile, StandardCopyOption.REPLACE_EXISTING); //If Dir$ already exists
}
catch(IOException e){
System.out.println(e.getMessage());
}
}