Easy Tutorial
❮ Thread Suspend Dir Current ❯

Java Example - Creating Temporary Files

Java Examples

The following example demonstrates how to create a temporary file in the default temporary directory using the createTempFile(String prefix, String suffix) method of the File class, where prefix is the prefix and suffix is the suffix:

Main.java File

import java.io.*;

public class Main {
    public static void main(String[] args) throws Exception {
        File temp = File.createTempFile("testtutorialprotmp", ".txt");
        System.out.println("File path: " + temp.getAbsolutePath());
        temp.deleteOnExit();
        BufferedWriter out = new BufferedWriter(new FileWriter(temp));
        out.write("aString");
        System.out.println("Temporary file created:");
        out.close();
    }
}

You can also specify the directory for the temporary file using the createTempFile(String prefix, String suffix, File directory) method with the directory parameter:

Main.java File

import java.io.File;

public class Main {
    public static void main(String[] args) {
        File f = null;

        try {
            // Create a temporary file
            f = File.createTempFile("tmp", ".txt", new File("C:/"));

            // Output the absolute path
            System.out.println("File path: " + f.getAbsolutePath());

            // Delete the temporary file on exit
            f.deleteOnExit();

            // Create another temporary file
            f = File.createTempFile("tmp", null, new File("D:/"));

            // Output the absolute path
            System.out.print("File path: " + f.getAbsolutePath());

            // Delete the temporary file on exit
            f.deleteOnExit();

        } catch (Exception e) {
            // Print the stack trace if an error occurs
            e.printStackTrace();
        }
    }
}

Java Examples

❮ Thread Suspend Dir Current ❯