java - 创建Temp文件的安全方法 [英] java - Safe way to create a Temp file
本文介绍了java - 创建Temp文件的安全方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种用安全方式在Java中创建临时文件的方法。安全,我的意思是:
I'm looking for a safe way to create a temp file in Java. By safe, I mean the following:
- 名称应该是唯一的,即使在潜在的竞争条件下(例如,另一个线程调用相同的函数)同时,或另一个进程同时运行此代码)
- 文件应该是私有的,即使在潜在的竞争条件下(例如,另一个用户尝试以高速率chmod文件)
- 我可以告诉它删除文件,而不必进行通用删除,并冒着删除错误文件的风险
- 理想情况下,应该确保文件被删除,即使在我有机会之前抛出异常
- 文件应该默认为一个理智的位置(例如JVM指定的tmp目录,默认为系统临时目录)
- 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)
推荐答案
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
这篇关于java - 创建Temp文件的安全方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文