Is there a standard and reliable way of creating a temporary directory inside a Java application? There's an entry in Java's issue database, which has a bit of code in the comments, but I wonder if there is a standard solution to be found in one of the usual libraries (Apache Commons etc.) ?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I got the same problem so this is just another answer for those who are interested, and it's similar to one of the above:
And for my application, I decided that to add in a option to clear the temp on exit so I added in a shut-down hook:
The method delete all subdirs and files before deleting the temp, without using the callstack (which is totally optional and you could do it with recursion at this point), but I want to be on the safe side.
Well, "createTempFile" actually creates the file. So why not just delete it first, and then do the mkdir on it?
I like the multiple attempts at creating a unique name but even this solution does not rule out a race condition. Another process can slip in after the test for
exists()
and theif(newTempDir.mkdirs())
method invocation. I have no idea how to completely make this safe without resorting to native code, which I presume is what's buried insideFile.createTempFile()
.Using
File#createTempFile
anddelete
to create a unique name for the directory seems ok. You should add aShutdownHook
to delete the directory (recursively) on JVM shutdown.This is the source code to the Guava library's Files.createTempDir(). It's nowhere as complex as you might think:
By default:
See here
If you are using JDK 7 use the new Files.createTempDirectory class to create the temporary directory.
Before JDK 7 this should do it:
You could make better exceptions (subclass IOException) if you want.