DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Install CMAK, Apache Kafka, Java 18, and Java 19 [Video Tutorials]
  • A Beginner's Guide to Back-End Development
  • Java and Low Latency
  • How to Check if a Java Project Depends on A Vulnerable Version of Log4j

Trending

  • The Human Side of Logs: What Unstructured Data Is Trying to Tell You
  • Hybrid Cloud vs Multi-Cloud: Choosing the Right Strategy for AI Scalability and Security
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  • How to Practice TDD With Kotlin
  1. DZone
  2. Coding
  3. Java
  4. Working With Temporary Files/Folders in Java

Working With Temporary Files/Folders in Java

By 
Anghel Leonard user avatar
Anghel Leonard
DZone Core CORE ·
Jan. 30, 20 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
76.5K Views

Join the DZone community and get the full member experience.

Join For Free

The Java NIO.2 API provides support for working with temporary folders/files. For example, we can easily locate the default location for temporary folders/files as follows:

Java
 




x


 
1
String defaultBaseDir = System.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).

In Linux/Unix, the global temporary directories are /tmp  and  /var/tmp . The preceding line of code will return the default location, depending on the operating system. Next, we'll learn how to create a temporary folder/file.

You may also like: Practical Guide for Converting Between Date and Temporal

Creating a Temporary Folder/File

Creating a temporary folder can be accomplished using:

  • Path createTempDirectory (Path dir, String prefix, FileAttribute<?>... attrs) 

This is a  static method in the Files  class that can be used as follows:

  • Let's create a temporary folder in the OS's default location with no prefix:
Java
 




xxxxxxxxxx
1


 
1
// C:\Users\Anghel\AppData\Local\Temp\8083202661590940905
2
Path tmpNoPrefix = Files.createTempDirectory(null);


  • Let's create a temporary folder in the OS's default location with a custom prefix:
Java
 




xxxxxxxxxx
1


 
1
// C:\Users\Anghel\AppData\Local\Temp\logs_5825861687219258744
2
String customDirPrefix = "logs_";
3
Path tmpCustomPrefix = Files.createTempDirectory(customDirPrefix);


  • Let's create a temporary folder in a custom location with a custom prefix:
Java
 




xxxxxxxxxx
1


 
1
// D:\tmp\logs_10153083118282372419
2
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
3
String customDirPrefix = "logs_";
4
Path tmpCustomLocationAndPrefix = Files.createTempDirectory(customBaseDir, customDirPrefix);



Creating a temporary file can be accomplished via:

  • Path createTempFile (Path dir, String prefix, String suffix, FileAttribute<?>... attrs

This is a static method in the Files  class that can be used as follows:

  • Let's create a temporary file in the OS's default location with no prefix and suffix:
Java
 




xxxxxxxxxx
1


 
1
// C:\Users\Anghel\AppData\Local\Temp\16106384687161465188.tmp
2
Path tmpNoPrefixSuffix = Files.createTempFile(null, null);


  • Let's create a temporary file in the OS's default location with a custom prefix and suffix:
Java
 




xxxxxxxxxx
1


 
1
// C:\Users\Anghel\AppData\Local\Temp\log_402507375350226.txt
2
String customFilePrefix = "log_";
3
String customFileSuffix = ".txt";
4
Path tmpCustomPrefixAndSuffix = Files.createTempFile(customFilePrefix, customFileSuffix);


  • Let's create a temporary file in a custom location with a custom prefix and suffix:
Java
 




xxxxxxxxxx
1


 
1
// D:\tmp\log_13299365648984256372.txt
2
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
3
String customFilePrefix = "log_";
4
String customFileSuffix = ".txt";
5
Path tmpCustomLocationPrefixSuffix 
6
    = Files.createTempFile(customBaseDir, customFilePrefix, customFileSuffix);



Next, we'll take a look at the different ways we can delete a temporary folder/file.

Deleting a Temporary Folder/File Via Shutdown-Hook

Deleting a temporary folder/file is a task that can be accomplished by the operating system or specialized tools. However, sometimes, we need to control this programmatically and delete a folder/file based on different design considerations.

A solution to this problem relies on the shutdown-hook mechanism, which can be implemented via the  Runtime.getRuntime().addShutdownHook() method. This mechanism is useful whenever we need to complete certain tasks (for example, cleanup tasks) right before the JVM shuts down. It is implemented as a Java thread whose  run()  method is invoked when the shutdown-hook is executed by JVM at shut down. This is shown in the following code:

Java
 




xxxxxxxxxx
1
31


 
1
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
2
String customDirPrefix = "logs_";
3
String customFilePrefix = "log_";
4
String customFileSuffix = ".txt";
5
    
6
try {
7
  Path tmpDir = Files.createTempDirectory(customBaseDir, customDirPrefix);
8
  Path tmpFile1 = Files.createTempFile(tmpDir, customFilePrefix, customFileSuffix);
9
  Path tmpFile2 = Files.createTempFile(tmpDir, customFilePrefix, customFileSuffix);
10
  
11
  Runtime.getRuntime().addShutdownHook(new Thread() {
12
    
13
    @Override
14
    public void run() {
15
      try (DirectoryStream<Path> ds = Files.newDirectoryStream(tmpDir)) {
16
        for (Path file: ds) {
17
          Files.delete(file);
18
        }
19
        
20
        Files.delete(tmpDir);
21
      } catch (IOException e) {
22
        ...
23
      }
24
    }
25
  });
26
  
27
  //simulate some operations with temp file until delete it
28
  Thread.sleep(10000);
29
} catch (IOException | InterruptedException e) {
30
  ...
31
}


A shutdown-hook will not be executed in the case of abnormal/forced terminations (for example, JVM crashes, Terminal operations are triggered, and so on). It runs when all the threads finish or when   System.exit(0)  is called. It is advisable to run it fast since they can be forcibly stopped before completion if something goes wrong (for example, the OS shuts down). Programmatically, a shutdown-hook can only be stopped by  Runtime.halt() .

Deleting a Temporary Folder/File via deleteOnExit()

Another solution for deleting a temporary folder/file relies on the File.deleteOnExit() method. By calling this method, we can register for the deletion of a folder/file. The deletion action happens when JVM shuts down:

Java
 




xxxxxxxxxx
1
26


 
1
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
2
String customDirPrefix = "logs_";
3
String customFilePrefix = "log_";
4
String customFileSuffix = ".txt";
5
    
6
try {
7
  Path tmpDir = Files.createTempDirectory(customBaseDir, customDirPrefix);
8
  System.out.println("Created temp folder as: " + tmpDir);
9
  Path tmpFile1 = Files.createTempFile(tmpDir, customFilePrefix, customFileSuffix);
10
  Path tmpFile2 = Files.createTempFile(tmpDir, customFilePrefix, customFileSuffix);
11
  
12
  try (DirectoryStream<Path> ds = Files.newDirectoryStream(tmpDir)) {
13
    tmpDir.toFile().deleteOnExit();
14
    
15
    for (Path file: ds) {      
16
      file.toFile().deleteOnExit();
17
    }
18
  } catch (IOException e) {
19
    ...
20
  }
21
  
22
  // simulate some operations with temp file until delete it
23
  Thread.sleep(10000);
24
} catch (IOException | InterruptedException e) {
25
  ...
26
}


It is advisable to only rely on this method (deleteOnExit()) when the application manages a small number of temporary folders/files. This method may consume a lot of memory (it consumes memory for each temporary resource that's registered for deletion) and this memory may not be released until JVM terminates.

Pay attention, since this method needs to be called in order to register each temporary resource, and the deletion takes place in reverse order of registration (for example, we must register a temporary folder before registering its content).

Deleting a Temporary File via DELETE_ON_CLOSE

Another solution when it comes to deleting a temporary file relies on  StandardOpenOption.DELETE_ON_CLOSE  (this deletes the file when the stream is closed). For example, the following piece of code creates a temporary file via the createTempFile() method and opens a buffered writer stream for it with DELETE_ON_CLOSE explicitly specified:

Java
 




xxxxxxxxxx
1
20


 
1
Path customBaseDir = FileSystems.getDefault().getPath("D:/tmp");
2
String customFilePrefix = "log_";
3
String customFileSuffix = ".txt";
4
Path tmpFile = null;
5
    
6
try {
7
  tmpFile = Files.createTempFile(
8
    customBaseDir, customFilePrefix, customFileSuffix);
9
} catch (IOException e) {
10
  ...
11
}
12
     
13
try (BufferedWriter bw = Files.newBufferedWriter(tmpFile,
14
       StandardCharsets.UTF_8, StandardOpenOption.DELETE_ON_CLOSE)) {
15
  
16
  //simulate some operations with temp file until delete it
17
  Thread.sleep(10000);
18
} catch (IOException | InterruptedException e) {
19
  ...
20
}


This solution can be adopted for any file. It is not specific to temporary resources.

The complete examples are available on GitHub under the prefix P142_foo.

If you enjoyed this article, then you'll love my book, Java Coding Problems, that contains a dedicated chapter including 20 problems dedicated to Java I/O.

Happy coding!

Further Reading

Practical Guide for Converting Between Date and Temporal

Java (programming language) Temporary file Temporary folder operating system

Opinions expressed by DZone contributors are their own.

Related

  • How To Install CMAK, Apache Kafka, Java 18, and Java 19 [Video Tutorials]
  • A Beginner's Guide to Back-End Development
  • Java and Low Latency
  • How to Check if a Java Project Depends on A Vulnerable Version of Log4j

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!