Copying files from one directory to another in Java
To copy a file from one directory to another in Java, you can use the Files.copy
method from the java.nio.file
package.
Here's an example of how you can use this method to copy a file:
Path source = Paths.get("/path/to/source/file.txt");
Path target = Paths.get("/path/to/target/file.txt");
try {
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
This code will copy the file at /path/to/source/file.txt
to /path/to/target/file.txt
, replacing the target file if it already exists.
If you want to copy the file and preserve the attributes of the original file, you can use the COPY_ATTRIBUTES
option in addition to the REPLACE_EXISTING
option:
Path source = Paths.get("/path/to/source/file.txt");
Path target = Paths.get("/path/to/target/file.txt");
try {
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException e) {
e.printStackTrace();
}
This code will copy the file and preserve the last modified time, owner, and permissions of the original file.
I hope this helps! Let me know if you have any questions.