【问题标题】:Why does this file not get deleted? [duplicate]为什么这个文件没有被删除? [复制]
【发布时间】:2013-08-18 04:34:00
【问题描述】:

我正在尝试使用File.delete() 删除文件

这是我的代码:

File stagingFile = new File(stagingPath,configFileName);
FileOutputStream fos = new FileOutputStream(stagingFile);
int c = 0;
while((c=input.read())!=-1){
    fos.write(c);
}
fos.flush();
fos.close();
input.close();

在执行了一些操作之后,我这样做了:

boolean delete = stagingFile.delete();

delete 返回错误。据我所知,我已经关闭了与stagingFile 相关的所有处理程序。我不知道为什么它没有被删除

【问题讨论】:

  • 您可以使用 Files.delete( [path] ) 方法在删除失败时获取 IOException,这应该会告诉您为什么无法删除文件。
  • 请注意,您的复制代码效率极低。在文件流周围使用BufferedInputStreamBufferedOutputStream,或从byte[] 数组读取/写入/从byte[] 数组读取/写入,注意正确使用read() 返回的计数。

标签: java


【解决方案1】:

来自File.delete docs

请注意,Files 类定义了 delete 方法以在无法删除文件时抛出 IOException。这对于错误报告和诊断无法删除文件的原因很有用。

试一试this method (Files.delete(Path))

【讨论】:

    【解决方案2】:

    另一个想法:首先使用createTempFile() 创建一个临时文件。之后,使用Files.delete() 删除文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2015-06-18
      • 2012-09-22
      • 1970-01-01
      • 2019-11-06
      相关资源
      最近更新 更多