位置:首頁 > Java技術 > java實例教學 > Java刪除文件

Java刪除文件

如何刪除一個文件?

解決方法

這個例子說明如何使用File類的delete()方法刪除文件。

import java.io.*;

public class Main {
   public static void main(String[] args)  {
      try {
         BufferedWriter out = new BufferedWriter
         (new FileWriter("filename"));
         out.write("aString1
");
         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:
filename (The system cannot find the file specified)
File does not exist or you are trying to read a 
file that has been deleted