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\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:
    filename (The system cannot find the file specified)
    File does not exist or you are trying to read a 
    file that has been deleted
    
    下面是另一个在 Java 中删除文件的示例
    
    import java.io.File;
    public class DeleteFileExample { 
       public static void main(String[] args) { 
          try { 
             File file = new File("C:\\Users\\TutorialsPoint7\\Desktop\\abc.txt");
             if(file.delete()) { 
                System.out.println(file.getName() + " is deleted!");
             } else {
                System.out.println("Delete operation is failed.");
             }
          } catch(Exception e) {
             e.printStackTrace();
          }
       }
    }
    
    上面的代码示例将产生以下结果。
    
    abc.txt is deleted!