有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何删除文件?

我使用以下代码删除文本文件。但它不会删除仍然存在的文件

File delfile=new File("SDS_DID.txt");
delfile.delete();

如何删除文件


共 (3) 个答案

  1. # 1 楼答案

    1. 尝试使用文件的绝对路径
    2. 确保您对该文件具有写入权限
    3. 档案。delete()返回一个布尔值,表示是否成功。检查这个值
  2. # 2 楼答案

    最常见的问题是找不到文件。 确保文件已经存在

    String fileName = "SDS_DID.txt";
    // A File object to represent the filename
    File f = new File(fileName);
    if (!f.exists) {
    JOptionPane.showErrorDialog (null , filename + " is not found.");
    }
    

    你不能只在硬盘上的任何地方拿起一个文件,你必须知道它实际上在哪里

  3. # 3 楼答案

    System.gc(); // close any streams first
    
      String fileName = "SDS_DID.txt";
    // A File object to represent the filename
    File f = new File(fileName);
    
    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
      throw new IllegalArgumentException(
          "Delete: no such file or directory: " + fileName);
    
    if (!f.canWrite())
      throw new IllegalArgumentException("Delete: write protected: "
          + fileName);
    
    
    // Attempt to delete it
    boolean success = f.delete();
    
    if (!success)
      throw new IllegalArgumentException("Delete: deletion failed");