Hello all – Hope you had wonderful Christmas holidays. Merry Christmas to all of you.
Also a very Happy New Year in advance. We are back after our long vacation. As you may have noticed long break on Crunchify, we are all back to start our new and existing journey again.
In this tutorial we will go over the best way to create Temporary file in Java.
Let’s create file CrunchifyJavaTempFile.java
- Next is to create
File()
object called crunchifyTempFile. Once we have it use functioncreateTempFile()
to create temporary filecruncnifyTemp.tmp
. - In this tutorial we will print absolute path to print temp file path
- In addition to that let’s print
- Canonical Path
- Parent
- Simple Path
- TotalSpace
- Name of the file
package crunchify.com.tutorial; import java.io.File; import java.io.IOException; /** * * @author Crunchify.com * Program: How to create Temporary file in Java using createTempFile? * Version: 1.0.1 */ public class CrunchifyJavaTempFile { public static void main(String str[]) { File crunchifyTempFile = null; try { crunchifyTempFile = File.createTempFile("crunchifyTemp", ".tmp"); // Returns the absolute pathname string of this abstract pathname. log("Temporary File Path : " + crunchifyTempFile.getAbsolutePath()); // Returns the canonical pathname string of this abstract pathname. log("Canonical File Path : " + crunchifyTempFile.getCanonicalPath()); // Returns the pathname string of this abstract pathname's parent. log("File Parent : " + crunchifyTempFile.getParent()); // Converts this abstract pathname into a pathname string. log("File Path : " + crunchifyTempFile.getPath()); // Returns the size of the partition named by this abstract pathname. log("Total Space : " + crunchifyTempFile.getTotalSpace()); // Returns the name of the file or directory denoted by this abstract pathname. log("Name of the File : " + crunchifyTempFile.getName()); } catch (IOException exception) { exception.printStackTrace(); } } private static void log(String string) { System.out.println(string); } }
Just copy above Java code into Eclipse and save file. Run program as a simple Java program and you should see below result.
Temporary File Path : /var/folders/8s/6y8s_v856rldwwfgbkwy2kqc0000gp/T/crunchifyTemp8820567565069738782.tmp Canonical File Path : /private/var/folders/8s/6y8s_v856rldwwfgbkwy2kqc0000gp/T/crunchifyTemp8820567565069738782.tmp File Parent : /var/folders/8s/6y8s_v856rldwwfgbkwy2kqc0000gp/T File Path : /var/folders/8s/6y8s_v856rldwwfgbkwy2kqc0000gp/T/crunchifyTemp8820567565069738782.tmp Total Space : 499313172480 Name of the File : crunchifyTemp8820567565069738782.tmp
Hope you find this tutorial helpful to create temporary file for your Enterprise Java program.