Java Example - Creating a Temporary File
The following example demonstrates using the createTempFile(String prefix, String suffix) method of the File class to create a temporary file in the default temporary directory. The parameter 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("testexampletmp", ".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 usecreateTempFile(String prefix, String suffix, File directory)the directory parameter in ... to specify the directory of the temporary file:
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 after termination
f.deleteOnExit();
//Create a 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 after termination
f.deleteOnExit();
} catch(Exception e) {
//If there are errors, output the content
e.printStackTrace();
}
}
}
Java Examples