In this example you’ll see how to copy a file using the new API provided in the JDK 7. The first step is to define the source
and the target
of the file to be copied. For this we can use the Path
class. To create an instance of Path
we use the Paths.get()
method by passing the path information as the arguments.
Next we can configure the file copy operation option. For this we can define it as an array of CopyOtion
. We can use copy option such as StandardCopyOption.REPLACE_EXISTING
and StandardCopyOption.COPY_ATTRIBUTES
.
Finally, to copy the file we use the Files.copy()
method. We give three arguments to this method, they are the source
file, the target
file and the copy options
information.
Let’s see the code snippet below:
package org.kodejava.io;
import java.io.IOException;
import java.nio.file.*;
public class NioFileCopyDemo {
public static void main(String[] args) {
// Define the source and target of the file to be copied.
Path source = Paths.get("D:/resources/data.txt");
Path target = Paths.get("D:/resources/data.bak");
// Define the options used in the file copy process.
CopyOption[] options = new CopyOption[]{
StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.COPY_ATTRIBUTES
};
try {
// Copy file from source to target using the defined
// configuration.
Files.copy(source, target, options);
} catch (IOException e) {
e.printStackTrace();
}
}
}
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024