Java MCQ: Which method is used to rename a file in Java?
Answer:
Explanation:
The renameTo()
method in Java is used to rename a file or directory. It is a method of the File
class, which is part of the java.io
package. This method allows you to rename a file by providing a new File
object representing the new name and location.
Here’s an example of how to use renameTo()
to rename a file:
import java.io.File;
public class RenameFileExample {
public static void main(String[] args) {
File oldFile = new File("oldName.txt");
File newFile = new File("newName.txt");
if (oldFile.renameTo(newFile)) {
System.out.println("File renamed successfully.");
} else {
System.out.println("Failed to rename the file.");
}
}
}
In this example, a File
object representing the old file name (oldName.txt
) is created, and a second File
object representing the new file name (newName.txt
) is also created. The renameTo()
method is then called on the old file object, with the new file object passed as an argument. If the rename operation is successful, a success message is printed. If the operation fails, a failure message is printed.
The renameTo()
method returns true
if the file was successfully renamed and false
otherwise. It is important to note that the renameTo()
method can also be used to move a file to a new directory if the new File
object specifies a different directory.
Overall, renameTo()
is a straightforward method for renaming files and directories in Java, making it an essential tool for file management operations.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html