Xóa file trong Java



Miêu tả vấn đề

Cách xóa một file trong Java?

Giải pháp

Ví dụ sau minh họa cách xóa một file bởi sử dụng phương thức delete() của lớp File trong Java.

import java.io.*;public class Main {
   public static void main(String[] args)  {
      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");
         }
      }
   }
}

Kết quả

Code trên sẽ cho kết quả sau:

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

file_trong_java.jsp