Java: Create Temporary Directory and File and Delete when application terminates

Post Banner

In this tutorial, we will create a temp directory and a file and delete them when the application terminates.

We have made use of the Files.createTempDirectory and Files.createTempFile to create a temporary directory and file respectively with a prefix and a random number that's added by the Java native logic!

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class JavaTempFileAndDirExample {

    private static Path tempDirPath;
    private static Path tempFilePath;

    public static void main(String[] args) throws InterruptedException, IOException {

        String pathStr = "/Users/code2care/my-projects-22/java-examples/";
        Path dirPathAndName = Paths.get(pathStr);
        try {
            //Step 1: Create Temp Directory
            tempDirPath = Files.createTempDirectory(dirPathAndName, "temp_");
            System.out.println("Temp Directory created: " + tempDirPath);

            //Step 2: Create Temp File
            tempFilePath = Files.createTempFile(tempDirPath, "temp_file_", ".txt");
            System.out.println("Temp File created: " + tempFilePath);

            //Step 3: Write some text to file
            Files.write(tempFilePath, "Hello".getBytes(), StandardOpenOption.APPEND);

            //Step 4: Do some logic!

            //Step 5: Delete temp file
            System.out.println("Temp file deleted..");

            //Step 6: Delete temp directory
            System.out.println("Work done deleting temp dir:" + tempDirPath);
        } catch (IOException e) {
            System.out.println("Error occurred while creating Directories!...");

Temp Directory created: /Users/code2care/my-projects-22/java-examples/temp_732237094777468206
Temp File created: /Users/code2care/my-projects-22/java-examples/temp_7322370947774682067/temp_file_5923746658607316240.txt
Temp file deleted..
Work done deleting temp dir:/Users/code2care/my-projects-22/java-examples/temp_7322370947774682067

This logic can be extended to create multiple temporary files and directories. Make sure to delete all the files within the directory before you delete the directory or else you will get SecurityException.

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap