Java 删除文件
创建于 2024-12-02 /
23
字体:
[默认]
[大]
[更大]
删除文件
要在 Java 中删除文件,请使用 delete()
方法:
实例
import java.io.File; // 导入 File 文件类
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("filename.txt");
if (myObj.delete()) {
System.out.println("Deleted the file: " + myObj.getName());
} else {
System.out.println("Failed to delete the file.");
}
}
}
输出将是:
Deleted the file: filename.txt
运行实例 »
删除文件夹
您也可以删除文件夹。 但是,它必须为空:
实例
import java.io.File;
public class DeleteFolder {
public static void main(String[] args) {
File myObj = new File("C:\Users\MyName\Test");
if (myObj.delete()) {
System.out.println("Deleted the folder: " + myObj.getName());
} else {
System.out.println("Failed to delete the folder.");
}
}
}
输出将是:
Deleted the folder: Test
运行实例 »
0 人点赞过