file.delete() 返回 false,即使 file.exists(), file.canRead(), file.canWrite(), file.canExecute() 都返回 true

2022-08-31 11:12:43

我试图删除一个文件,在里面写了一些东西,用.这是我用来编写的代码:FileOutputStream

private void writeContent(File file, String fileContent) {
    FileOutputStream to;
    try {
        to = new FileOutputStream(file);
        to.write(fileContent.getBytes());
        to.flush();
        to.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

如您所见,我刷新并关闭了流,但是当我尝试删除时,返回 false。file.delete()

我在删除之前检查了该文件是否存在,并且:,都返回true。就在调用这些方法之后,我尝试返回 false。file.exists()file.canRead()file.canWrite()file.canExecute()file.delete()

我做错了什么吗?


答案 1

Java中的另一个错误。我很少找到它们,只有我10年职业生涯中的第二个。正如其他人所提到的,这是我的解决方案。我用了下界。但在这里,就我而言,这绝对是至关重要的。奇怪?是的!System.gc()

finally
{
    try
    {
        in.close();
        in = null;
        out.flush();
        out.close();
        out = null;
        System.gc();
    }
    catch (IOException e)
    {
        logger.error(e.getMessage());
        e.printStackTrace();
    }
}

答案 2

这是相当奇怪的技巧,有效的。问题是,当我以前阅读过文件的内容时,我使用了.阅读后,我关闭了缓冲区。BufferedReader

同时,我切换了,现在我正在阅读内容使用.同样在读完之后,我关闭了流。现在它正在工作。FileInputStream

问题是我对此没有解释。

我不知道,而且不兼容。BufferedReaderFileOutputStream