在java编程中,如何删除文件?
此示例显示如何使用File
类的delete()
方法删除文件。
package com.yiibai;
import java.io.*;
public class DeleteFile {
public static void main(String[] args) {
String filename = "be-delete-file.txt";
try {
BufferedWriter out = new BufferedWriter (new FileWriter(filename));
out.write("aString1\n");
out.close();
boolean success = (new File(filename)).delete();
if (success) {
System.out.println("The file has been successfully deleted");
}
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}catch (IOException e) {
System.out.println("exception occoured"+ e);
System.out.println("File does not exist or you are trying to read a file that has been deleted");
}
}
}
执行上述示例代码,将产生以下结果 -
The file has been successfully deleted
exception occouredjava.io.FileNotFoundException: be-delete-file.txt (系统找不到指定的文件。)
File does not exist or you are trying to read a file that has been deleted
示例-2
以下是删除一个文件的另一个示例。
package com.yiibai;
import java.io.File;
public class DeleteFile2 {
public static void main(String[] args) {
try {
File file = new File("F:/worksp/javaexamples/java_files/afile.txt");
if (file.delete()) {
System.out.println(file.getName() + " is deleted!");
} else {
System.out.println("Delete operation is failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
执行上述示例代码,将产生以下结果 -
afile.txt is deleted!