【问题标题】:Why is a file not getting deleted using the file.delete() function?为什么使用 file.delete() 函数没有删除文件?
【发布时间】:2014-11-15 11:27:21
【问题描述】:

我正在使用一种方法来删除特定的预先存在的文件,使用 file.delete() 方法如下

public void deleteFile(String fileName)throws IOException  //To refine. Does not work
{
    File file=new File("C:\\File Handling\\"+fileName+".txt");
    boolean success=file.delete();
    System.out.println(success);
}

但是,成功总是返回 false。 出了什么问题?

请告知如何使用 java 删除文件。

【问题讨论】:

  • 您可能想在其中添加一个 .exists() 检查并首先检查写入权限等。

标签: java file-handling


【解决方案1】:

在 Windows 上,您通常无法删除任何进程打开的文件。此外,您可能想通过从命令行执行删除来检查您是否有权限。

【讨论】:

    【解决方案2】:

    您的代码在我的机器上运行良好。我只是将它包装在一个类中并使其静态以由 main() 调用

    public static void main(String[] args) throws IOException {
            deleteFile("newfile");
        }
    
        public static void deleteFile(String fileName)throws IOException  //To refine. Does not work
        {
            File file=new File("C:\\File Handling\\"+fileName+".txt");
            boolean success=file.delete();
            System.out.println(success);
        }
    

    【讨论】:

      【解决方案3】:

      有时,windows 处理文件的方式可能很奇怪,请尝试使用 deleteOnExit() 方法,这样可以确保程序在代码中仍然没有打开。在运行代码之前,您是否仔细检查了该文件是否未在其他程序中打开?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多