在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!