How to create temporary files in Java

In Java, you can use the createTempFile method of the java.io.File class to create a temporary file. This method will create a new temporary file in the default temporary file directory and return a File object to represent this temporary file.

Here is a sample code:

import java.io.File;
import java.io.IOException;

public class CreateTempFileExample {
    public static void main(String[] args) {
        try {
            // 创建一个临时文件
            File tempFile = File.createTempFile("temp", ".txt");
            
            // 打印临时文件的路径
            System.out.println("临时文件路径:" + tempFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Running the above code will create a temporary file with the prefix “temp” and the suffix “.txt”, then print out the path of the temporary file.

Please note that this temporary file will be deleted after the program execution ends. If you want to preserve the temporary file, you can use the deleteOnExit method to set it to be deleted when the program exits.

tempFile.deleteOnExit();

Hope this helps you!

bannerAds