What is a safe way to create a Temp file in Java?

二次信任 提交于 2019-12-18 10:44:10

问题


I'm looking for a safe way to create a temp file in Java. By safe, I mean the following:

  • Name should be unique, even under potential race conditions (e.g. another Thread calls the same func at the same time, or another process runs this code simultaneously)
  • File should be private, even under potential race conditions (e.g. another user tries to chmod file at high rate)
  • I can tell it to delete the file, without me having to do a generic delete, and risk deleting the wrong file
  • Ideally, should ensure file is deleted, even if exception is thrown before I get the chance to
  • File should default to a sane location (e.g. the JVM specified tmp dir, defaulting to the system temp dir)

回答1:


Use File.createTempFile().

File tempFile = File.createTempFile("prefix-", "-suffix");
//File tempFile = File.createTempFile("MyAppName-", ".tmp");
tempFile.deleteOnExit();

Will create a file in the temp dir, like:

prefix-6340763779352094442-suffix




回答2:


Since Java 7 there is the new file API "NIO2" which contains new methods for creating temnp files and directories. See

  • createTempDirectory
  • createTempDirectory
  • createTempFile
  • createTempFile

e.g.

Path tempDir = Files.createTempDirectory("tempfiles");

or

Path tempFile = Files.createTempFile("tempfiles", ".tmp");


来源:https://stackoverflow.com/questions/26860167/what-is-a-safe-way-to-create-a-temp-file-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!