How to Get Temp Directory Path in Java

In this post, we will see how to get temp directory path in java.

Get Temp Directory Path in Java

Using System.getProperty()

To get the temp directory path, you can simply use System.getProperty("java.io.tmpdir"). It will return default temporary folder based on your operating system.

Default temp directory path
Windows : %USER%\AppData\Local\Temp
Linux/Unix: /tmp

Let’s see with the help of example:

Output:

By Creating Temp File and Extracting Temp Path

We can also create temp file and extract temp directory path using String’s substring() method.

Using java.io.File

To get temp directory path:

  • Use File.createTempFile() to create temp file.
  • Get absolute path using File's getAbsolutePath() method.
  • Use substring() method to extract temp directory path from absolute path.

Output:

Using java.nio.File.Files

To get temp directory path:

  • Use Files.createTempFile() to create temp file.
  • Get absolute path using toString() method.
  • Use substring() method to extract temp directory path from absolute path.

Output:

Override Default Temp Directory Path

If you want to override temp directory path, you can run java program with JVM arguments as -Djava.io.tmpdir=Temo_file_path

For example:
If you want set temp directory path as C:\temp, you can run java program with JVM argument as -Djava.io.tmpdir=C:\temp

That’s all about how to get temp directory path in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *