deleteOnExit 在关闭写入文件的流之后仍未删除文件。

huangapple go评论153阅读模式
英文:

deleteOnExit not deleting file despite closing of stream writing to it

问题

以下是翻译好的部分:

Relevant piece of code:

    File tempFile = File.createTempFile("", "");
    tempFile.deleteOnExit();
    FileOutputStream out = new FileOutputStream(tempFile);
    byte[] bytes = IOUtils.toByteArray(inputStream);
    out.write(bytes);
    out.close();

I'm running this as a local tomcat server run configuration via IntelliJ, and on quitting the server, it doesn't clean up the temp file. Any ideas on what I might be missing?
英文:

Relevant piece of code:

File tempFile = File.createTempFile("", "");
tempFile.deleteOnExit();
FileOutputStream out = new FileOutputStream(tempFile);
byte[] bytes = IOUtils.toByteArray(inputStream);
out.write(bytes);
out.close();

I'm running this as a local tomcat server run configuration via IntelliJ, and on quitting the server, it doesn't clean up the temp file. Any ideas on what I might be missing?

答案1

得分: 1

File.deleteOnExit() 方法会在当前虚拟机上安装一个关机挂钩,因此只有在虚拟机执行正常的受控关机时才会触发删除操作。

对于 TOMCAT,可以通过 TOMCAT 安装目录下的 bin\shutdown.batbin/shutdown.sh 脚本来执行正常关机。

然而,如果你的 TOMCAT 服务器可能运行非常长的时间,你应该完全避免调用 File.deleteOnExit(),因为要删除的文件会存储在一个列表中,这个列表可能(最终)增长到巨大的大小,导致 OutOfMemoryError。

对于频繁重新启动的 Tomcat 实例,这不会成为问题,但对于高负载应用服务器来说,这将是一个问题。如果需要采用不同的方法,更可靠的方式是在 try...finally 块中跟踪准备删除的临时文件:

File temp = null;
try {
    // ...
    temp = File.createTempFile("", "");
    // ...
} finally {
    deleteOnExit(temp);
}

private static void deleteOnExit(File fileToDelete) {
    if (fileToDelete != null)
        fileToDelete.delete();
}
英文:

The File.deleteOnExit() installs a shutdown hook on the current VM so your delete is only triggered if the VM performs a normal controlled shutdown.

For TOMCAT that would be via the bin\shutdown.bat or bin/shutdown.sh scripts within the TOMCAT installation.

However if your TOMCAT server could be running for very long periods you should avoid calling File.deleteOnExit() altogether as the files to delete are stored in a List which could (eventually) grow to huge size and lead to OutOfMemoryError.

This will not be a problem for a Tomcat instance that is re-started frequently, but would be an issue for high volume application server. If this different approach is needed, it is more reliable to keep track of temp files that are ready to delete in try...finally:

File temp = null;
try {
    ...
    temp = File.createTempFile("", "") ...
    ...
} finally {
    deleteOnExit(temp);
}

private static void deleteOnExit(File fileToDelete)
{
    if (fileToDelete != null)
        fileToDelete.delete();
}

huangapple
  • 本文由 发表于 2020年7月21日 23:24:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/63017828.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定