How to create a temporary directory/folder in Java?
To create a temporary directory/folder in Java, you can use the createTempDirectory()
method of the Files
class in the java.nio.file
package. This method creates a new directory in the default temporary-file directory and returns a Path
object pointing to the new directory.
Here is an example of how to create a temporary directory in Java:
Path tempDir = Files.createTempDirectory("temp");
System.out.println(tempDir); // prints the path of the temporary directory
You can also specify a prefix and a suffix for the temporary directory by passing them as arguments to the createTempDirectory()
method. For example:
Path tempDir = Files.createTempDirectory("prefix-", "-suffix");
System.out.println(tempDir); // prints the path of the temporary directory
The createTempDirectory()
method throws an IOException
if an I/O error occurs while creating the temporary directory.
I hope this helps. Let me know if you have any questions.