

Java 8 NIO provide way to create Temporary file System Temp directory. Here is example of Java create temporary file using java nio. Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.
Table of Contents
1. Java Create Temporary File using java.nio.file.Files
try { Path path = Files.createTempFile("Prefix_","_Postfix"); // it will create temp file and return path of it System.out.println(path.toString()); }catch (Exception e){ e.printStackTrace(); }
Output:
C:\Users\javadeveloperzone\AppData\Local\Temp\Prefix_17837843845625492472_Postfix
2. Java Create Temporary File using java.io.File
Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name. It will direct return file object so we can perform operation on temp file.
try { File tempFile = File.createTempFile("Prefix_","_Postfix"); // it will create temp file and return file System.out.println(tempFile.getAbsolutePath()); }catch (Exception e){ e.printStackTrace(); }
C:\Users\javadeveloperzone\AppData\Local\Temp\Prefix_4713480329263426311_Postfix
References:
https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html
https://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html
Was this post helpful?
Let us know if you liked the post. That’s the only way we can improve.