个人博客导航页(点击右侧链接即可打开个人博客):大牛带你入门技术栈
有没有在Java应用程序内部创建临时目录的标准可靠方法? Java的问题数据库中有一个条目,注释中包含一些代码,但是我想知道在一个常用的库(Apache Commons等)中是否找到标准解决方案?
#1楼
这是我决定为自己的代码执行的操作:
/**
* Create a new temporary directory. Use something like
* {@link #recursiveDelete(File)} to clean this directory up since it isn't
* deleted automatically
* @return the new directory
* @throws IOException if there is an error creating the temporary directory
*/
public static File createTempDir() throws IOException
{
final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
File newTempDir;
final int maxAttempts = 9;
int attemptCount = 0;
do
{
attemptCount++;
if(attemptCount > maxAttempts)
{
throw new IOException(
"The highly improbable has occurred! Failed to " +
"create a unique temporary directory after " +
maxAttempts + " attempts.");
}
String dirName = UUID.randomUUID().toString();
newTempDir = new File(sysTempDir, dirName);
} w