How to delete a file based on its file path in Java?
In Java, you can use the delete() method of the java.io.File class to delete a file based on its file path. This method returns a boolean value indicating whether the file was successfully deleted. Here is an example code:
import java.io.File;
public class DeleteFileExample {
public static void main(String[] args) {
String filePath = "C:/path/to/file.txt";
File file = new File(filePath);
if (file.delete()) {
System.out.println("文件删除成功");
} else {
System.out.println("文件删除失败");
}
}
}
In the example above, a File object is first created by passing in the path of the file. Then, the delete() method is called to delete the file. If the file is successfully deleted, the delete() method will return true, otherwise it will return false. Based on the return value, we can determine whether the deletion operation was successful.