Java MCQ: How can you copy a file in Java?
Answer:
Explanation:
The Files.copy()
method, available in the java.nio.file
package, is used to copy files or directories in Java. This method provides a simple and efficient way to copy the contents of a file from one location to another.
Here’s an example of how to use Files.copy()
to copy a file:
import java.nio.file.*;
public class CopyFileExample {
public static void main(String[] args) {
Path source = Paths.get("source.txt");
Path destination = Paths.get("destination.txt");
try {
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully.");
} catch (IOException e) {
System.out.println("An error occurred during the file copy.");
e.printStackTrace();
}
}
}
In this example, Files.copy()
is used to copy the contents of source.txt
to destination.txt
. The StandardCopyOption.REPLACE_EXISTING
option is specified to replace the destination file if it already exists. If no such option is provided, an exception will be thrown if the destination file exists.
The Files.copy()
method is part of the java.nio.file
package, introduced in Java 7 as part of the NIO.2 (New I/O) API. This package provides advanced file operations that are more flexible and efficient than the traditional java.io
package.
Using Files.copy()
, you can copy files or directories, preserving file attributes and ensuring that the operation is performed atomically. This method is ideal for applications that require reliable file copying with options for handling existing files and preserving metadata.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html