Java MCQ: Which method is used to delete a file in Java?
Answer:
Explanation:
The delete()
method in Java is used to delete a file or an empty directory. It is a method of the File
class, which is part of the java.io
package. When delete()
is called on a File
object, it attempts to delete the file or directory represented by that object.
Here’s an example of how to use delete()
to delete a file:
import java.io.File;
public class DeleteFileExample {
public static void main(String[] args) {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("Deleted the file: " + file.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
In this example, a File
object is created to represent the file example.txt
. The delete()
method is then called on this object. If the file is successfully deleted, a success message is printed. If the file could not be deleted (for example, if it does not exist), a failure message is printed instead.
The delete()
method returns true
if the file or directory was successfully deleted and false
otherwise. It’s important to note that delete()
will not delete non-empty directories; it can only delete empty directories or individual files.
Overall, the delete()
method is a simple and effective way to remove files or empty directories in Java, making it a key part of file management operations.
Reference links:
https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html