Get System Temporary Directory in Java using Apache Commons IO

Tags: FileUtils Apache Commons Apache Commons IO Temp File Directory

In this Java tutorial we learn how to get the system temporary directory using FileUtils class of Apache Commons IO library.

How to add Apache Commons IO library to your Java project

To use the Apache Commons IO library in the Gradle build project, add the following dependency into the build.gradle file.

implementation 'commons-io:commons-io:2.8.0'

To use the Apache Commons IO library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.8.0</version>
</dependency>

To have more information about the Apache Commons IO library you can visit the library home page at commons.apache.org/proper/commons-io/

How to get Temporary Directory in Java using FileUtils class

We can use the method FileUtils.getTempDirectory() to get a temporary directory as a File object.

GetTempDirectory.java

import org.apache.commons.io.FileUtils;

import java.io.File;

public class GetTempDirectory {
    public static void main(String... args) {
        File tempDirectory = FileUtils.getTempDirectory();

        System.out.println("Temporary directory is " + tempDirectory);
    }
}
The output is:
Temporary directory is C:\Users\MyPC\AppData\Local\Temp

Apache Commons IO library also provides the method FileUtils.getTempDirectoryPath() to get the temporary directory path as a String value.

GetTempDirectoryPath.java

import org.apache.commons.io.FileUtils;

public class GetTempDirectoryPath {
    public static void main(String... args) {
        String tempDirectoryPath = FileUtils.getTempDirectoryPath();

        System.out.println("Temporary directory path is " + tempDirectoryPath);
    }
}
The output is:
Temporary directory path is C:\Users\MyPC\AppData\Local\Temp\

Happy Coding 😊