在 Java 中创建临时文件的安全方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26860167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:24:26  来源:igfitidea点击:

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

javatemporary-files

提问by SRobertJames

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

我正在寻找一种在 Java 中创建临时文件的安全方法。安全,我的意思是:

  • 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)
  • 名称应该是唯一的,即使在潜在的竞争条件下(例如,另一个线程同时调用相同的函数,或者另一个进程同时运行此代码)
  • 文件应该是私有的,即使在潜在的竞争条件下(例如另一个用户试图以高速率 chmod 文件)
  • 我可以告诉它删除文件,而不必进行通用删除,并且冒着删除错误文件的风险
  • 理想情况下,应该确保文件被删除,即使在我有机会之前抛出异常
  • 文件应该默认到一个合理的位置(例如 JVM 指定的 tmp 目录,默认为系统临时目录)

采纳答案by Stefan

Use File.createTempFile().

使用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

prefix-6340763779352094442-suffix

回答by Tim Büthe

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

从 Java 7 开始,就有了新的文件 API“NIO2”,其中包含用于创建 temnp 文件和目录的新方法。看

e.g.

例如

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

or

或者

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