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.io.IOException;
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!
            Thread.sleep(5000);

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

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

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.



Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.