java - 执行操作后无法删除文件

标签 java

即使关闭相应的读取器和写入器也无法删除文件。 文件上存在权限 file.delete() 返回 false 我的代码

main(){
        try{
        File file=new File(path);// Path where the file is present
        FileReader reader = new FileReader(path); 
        BufferedReader br = new BufferedReader(reader); 
        FileWriter writer = new FileWriter(pathOther);
        BufferedWriter wr = new BufferedWriter(writer);
        // Readers and writers for i/o operations
       while((String str=br.readLine())!=null){ 
       wr.write(str);                    // Copying to another file
       }
       }catch(Exception e){}
       finally{
        reader.close(); //close reader

        writer.close(); //close writer
        file.delete(); //This returns false

}

最佳答案

猜测发生的情况是,您关闭了FileInputStream,但让BufferedReader保持打开状态,这会留下一些东西文件句柄。然后,当您尝试删除该文件时,它会返回 false,因为其他东西拥有该文件的句柄。

尝试以下代码:

File file = new File(path);
try {
    br = new BufferedReader(new FileReader(file));

    // use the reader ...
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (br != null) br.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

// now close the file
file.delete();

更新:

在测试上述代码时,我注意到其他一些东西也可能导致您所看到的观察结果。如果 path 处的文件不存在,那么逻辑上调用 file.delete 也会因此失败。因此,在尝试删除该文件之前,您应该确保该文件确实存在。您可以调用 file.exists() 来检查这一点。

关于java - 执行操作后无法删除文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39447897/

相关文章:

java - 在java中获取列表元素的最后一部分

java - 仅使用 @Transactional 时,持久性单元未启动

java - Java 中 "public static final"常量的 Clojure 等价物是什么

java - Spring的事件模型

java - Apache Ivy 设置任务和 ivysettings.xml 文件

java - 如何将 ExpandableListView 的选定项目存储在 ArrayList 中

java - json 请求枚举

java - 使用 MinGW64 的 JAWT 应用程序无法运行

java - java GUI创建的线程安全问题

Java -install 与 PATH