【问题标题】:Can't delete file after it gets written文件写入后无法删除
【发布时间】:2015-07-15 03:39:48
【问题描述】:

我先放我的代码:

@Post
public Representation post(InputStream zip) throws Throwable {
    createFile(zip, "C:/temp");
    return new StringRepresentation("File uploaded");
}    

public void createFilee(InputStream zipStream, uploadedFileLocation) throws Exception {
    try {
        writeToFile(zipStream, uploadedFileLocation);
        FileUtils.forceDelete(new File(uploadedFileLocation));
        } catch (Exception e) {
             throw e;
        }
}


private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
    try {
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
        uploadedInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

当我将文件发送到我的服务器时,它无法被删除。使用FileUtils.forceDelete() 时,表示无法删除该文件。在服务器尝试使用文件实用程序删除文件后,我可以在服务器仍在运行时手动删除文件。为什么不能自己删除?!有任何想法吗?谢谢

编辑:问题可能是来自 POST 的 InputStream 在 POST 返回之前还存在吗?那么,即使我调用删除文件,POST 仍然使流保持活动状态?这甚至可能吗?

【问题讨论】:

  • 文件可能存在权限问题?
  • 我注意到有时在关闭文件然后立即尝试访问它们时有时会在某些机器上导致奇怪的行为,例如防病毒软件会在您打开文件一毫秒后执行某些操作关闭它。我知道这是一个糟糕的长期解决方案,但请查看在尝试删除之前添加睡眠是否可以解决问题。
  • 问题可能是来自 POST 的 InputStream 在 POST 返回之前一直存在吗?那么,即使我调用删除文件,POST 仍然使流保持活动状态?这甚至可能吗?
  • @StephenD 为什么要实例化两次?是错字吗?
  • 文件创建后为什么要立即删除?

标签: java file inputstream delete-file


【解决方案1】:

在我有限的 Windows 体验中,它可能是两件事之一

我会检查 1) 杀毒软件正在尝试扫描文件 2)某种索引器(系统或自定义)正在尝试索引文件。

您可以使用 processExplorer 之类的工具来查看哪个进程占用了文件描述符。 http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

【讨论】:

  • 问题可能是来自 POST 的 InputStream 在 POST 返回之前一直存在吗?那么,即使我调用删除文件,POST 仍然使流保持活动状态?这甚至可能吗?
猜你喜欢
  • 1970-01-01
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 2017-02-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多