Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a temporary directory/folder in Java?

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.) ?

like image 367
Peter Becker Avatar asked Mar 06 '09 01:03

Peter Becker


People also ask

How do you create a temporary folder?

Open your File Explorer (it's usually the first button on your desktop taskbar, looks like a folder). Go to the "This PC" section on the left, and then double-click your C: drive. On the Home tab at the top, click "New Folder" and name it "Temp".

Where does Java store temp files?

getProperty("java. io. tmpdir"); Commonly, in Windows, the default temporary folder is C:\Temp , %Windows%\Temp , or a temporary directory per user in Local Settings\Temp (this location is usually controlled via the TEMP environment variable).

How do you create a new directory in Java?

In Java, the mkdir() function is used to create a new directory. This method takes the abstract pathname as a parameter and is defined in the Java File class. mkdir() returns true if the directory is created successfully; else, it returns false​.

What is Java IO Tmpdir?

io. tmpdir is a standard Java system property which is used by the disk-based storage policies. It determines where the JVM writes temporary files, including those written by these storage policies (see Section 4 and Appendix A. 8). The default value is typically " /tmp " on Unix-like platforms.


1 Answers

If you are using JDK 7 use the new Files.createTempDirectory class to create the temporary directory.

Path tempDirWithPrefix = Files.createTempDirectory(prefix); 

Before JDK 7 this should do it:

public static File createTempDirectory()     throws IOException {     final File temp;      temp = File.createTempFile("temp", Long.toString(System.nanoTime()));      if(!(temp.delete()))     {         throw new IOException("Could not delete temp file: " + temp.getAbsolutePath());     }      if(!(temp.mkdir()))     {         throw new IOException("Could not create temp directory: " + temp.getAbsolutePath());     }      return (temp); } 

You could make better exceptions (subclass IOException) if you want.

like image 105
TofuBeer Avatar answered Sep 28 '22 10:09

TofuBeer