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: /tmpWhat 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.jarAlternatively, you can use the JAVA_TOOL_OPTIONS environment variable, which is useful in containerized environments where you can't easily modify the JVM arguments:
export JAVA_TOOL_OPTIONS="-Djava.io.tmpdir=$TEMP_DIR"
java -jar my-app.jarTrailing slash inconsistency
Be aware that the value returned by java.io.tmpdir may or may not include a trailing slash depending on the platform.
Tip
Always use java.io.File or java.nio.file.Path to construct file paths instead of string concatenation to avoid issues.
