How to get the temporary directory path in Java
To get the temporary directory path in Java you can use the java.io.tmpdir
system property.
The JVM sets this property when it starts and points to the default temporary directory for the operating system.
System.getProperty("java.io.tmpdir");
The following code snippet shows a simple program that logs the temporary directory when the application starts:
public class TempDir {
public static void main(String[] args) {
System.out.println("Temporary directory: " + System.getProperty("java.io.tmpdir"));
}
}
When executed, the program will output the following:
Temporary directory: /tmp
What are the default temporary directories for each operating system?
- Windows:
%USERPROFILE%\AppData\Local\Temp
- Linux:
/tmp
- macOS:
/tmp
How to change the temporary directory path in Java?
The JVM automatically sets the temporary directory path as a system property.
However, you can change it by setting the java.io.tmpdir
property to the desired path when starting the JVM.
java -Djava.io.tmpdir=$TEMP_DIR -jar my-app.jar