Java MCQ: Which method is used to move a file in Java?
Answer:
Explanation:
The Files.move()
method, available in the java.nio.file
package, is used to move files or directories from one location to another in Java. This method can also be used to rename files or directories, as moving a file to a new path effectively changes its name.
Here’s an example of how to use Files.move()
to move a file:
import java.nio.file.*;
public class MoveFileExample {
public static void main(String[] args) {
Path source = Paths.get("source.txt");
Path destination = Paths.get("destination.txt");
try {
Files.move(source, destination, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File moved successfully.");
} catch (IOException e) {
System.out.println("An error occurred during the file move.");
e.printStackTrace();
}
}
}
In this example, Files.move()
is used to move the file source.txt
to the new location destination.txt
. The StandardCopyOption.REPLACE_EXISTING
option is specified to overwrite the destination file if it already exists. If this option is not provided, an exception will be thrown if the destination file exists.
The Files.move()
method is part of the NIO.2 API, introduced in Java 7, which provides advanced file operations that are more efficient and flexible than the traditional java.io
package. This method can handle moving large files or directories atomically, ensuring that the operation is completed without partial updates.
Using Files.move()
, you can move or rename files and directories while preserving file attributes. This method is essential for applications that require reliable file operations, such as organizing files, renaming files, or migrating data.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html