Create temporary file Java
In below example we will create temporary file and write some content in it and verify by opening this file from temporary location:
- Sample java class:
package com.javahonk; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class CreateTempFileJava { public static void main(String[] args) { try { // Creates an empty file in the default temporary-file directory, // using the given prefix and suffix to generate its name File tempFile = File.createTempFile("temproryFileByJava", ".tmp"); System.out.println(tempFile.getAbsolutePath()); FileWriter fw = new FileWriter(tempFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); for (int i = 0; i < 10; i++) { bw.write("Write to temp file"); bw.newLine(); } bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
- Output:
For more information please refer oracle documentation here