How do I create temporary file?

A temporary file can be created by using method. It accepts the prefix, suffix and the path where the file will be stored. When no path is specified it will use the platform default temporary folder.

The name of the temporary file will be in the form of prefix plus five or more random characters plus the suffix. When the suffix is null a default .tmp will be used for suffix.



public class TemporaryFileDemo {
    public static void main(String[] args) throws Exception {
        // Create a temporary file userlist.txt in the default platform
        // temporary folder / directory. We can get the platform temporary
        // folder using System.getProperty("")
        File user = File.createTempFile("userlist", ".txt");

        // Delete the file when the virtual machine is terminated.

        // Create a temporary file data.txt in the user specified folder.
        File data = File.createTempFile("data", ".txt", new File("C:/Users/kodejava/Data"));

        // Write data into temporary file
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(data))) {

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.