Tuesday, October 1, 2019

Creating Temporary File in Java

Sometimes you may want to create temporary file in Java to store some data for the application. Once the job is done temp file can safely be discarded or you can delete it on exit. In this post we'll see how to create a temporary file in Java and how to read and write to temporary file.

In java.io.File class there are two methods for creating a temp file.

  • static File createTempFile(String prefix, String suffix, File directory)- Creates a new empty file in the specified directory, using the passed prefix and suffix strings to generate file name.
  • static File createTempFile(String prefix, String suffix)- Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

In java.nio.file.Files class also there are two methods for creating temporary files.

  • static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs)- Creates a new empty file in the specified directory, using the given prefix and suffix strings to generate its name. You can also pass an optional list of file attributes to set atomically when creating the file
  • static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs)- Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

Creating temporary file using java.io.File class methods

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

public class TempFile {

 public static void main(String[] args) {
  try {
   // Using default directory
   File tempFile = File.createTempFile("MyFile", ".temp");
   System.out.println("Temp file path- " + tempFile.getCanonicalPath());
   // Specifying directory
   File testFile = File.createTempFile("MyFile", ".temp", new File("F:\\Temp"));
   System.out.println("Temp file path- " + testFile.getCanonicalPath());
   
   tempFile.deleteOnExit();
   testFile.deleteOnExit();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Output

Temp file path- C:\Users\netjs\AppData\Local\Temp\MyFile13999667283141733746.temp
Temp file path- F:\Temp\MyFile11668072031090823667.temp

Creating temporary file using java.nio.file.Files class methods

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class TempFile {

 public static void main(String[] args) {
  try {
   // Using default directory
   Path tempFile = Files.createTempFile("MyFile", ".temp");
   System.out.println("Temp file path- " + tempFile);
   // Specifying directory
   Path testFile = Files.createTempFile(Path.of("F:\\Temp"), "MyFile", ".temp");
   System.out.println("Temp file path- " + testFile);
   // Read write temp file operations
   
   // delete file on exit
   tempFile.toFile().deleteOnExit();
   testFile.toFile().deleteOnExit();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Output

Temp file path- C:\Users\Anshu\AppData\Local\Temp\MyFile2647482374773079441.temp
Temp file path- F:\Temp\MyFile16822359990880283479.temp

Reading and writing temporary file in Java

Once the temporary file is created you will of course use it to write some data and read some data from the temp file. You can use BufferedWriter and BufferedReader for writing to and reading from a temp file.

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class TempFile {

 public static void main(String[] args) {
  try {
   // Specifying directory
   File testFile = File.createTempFile("MyFile", ".temp", new File("F:\\Temp"));
   System.out.println("Temp file path- " + testFile.getCanonicalPath());
   testFile.deleteOnExit();
   // Writing to temp file
   BufferedWriter bw = new BufferedWriter(new FileWriter(testFile));
   bw.write("Writing to the temp file");
   bw.close();
   // Reading from temp file
   String str;
   BufferedReader br = new BufferedReader(new FileReader(testFile));
   while((str = br.readLine()) != null){
    System.out.println("Line is - " + str);
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } 
 }
}

Output

Temp file path- F:\Temp\MyFile16468233438314323721.temp
Line is - Writing to the temp file

That's all for this topic Creating Temporary File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Buffered Streams in Java IO
  2. How to Create Password Protected Zip File in Java
  3. Compress And Decompress File Using GZIP Format in Java
  4. Reading File in Java Using Files.lines And Files.newBufferedReader
  5. How to Read File From The Last Line in Java

You may also like-

  1. LinkedBlockingDeque in Java
  2. Difference Between sleep And wait in Java Multi-Threading
  3. Functional Interfaces in Java
  4. Equality And Relational Operators in Java
  5. Type Wrapper Classes in Java
  6. Connection Pooling With Apache DBCP Spring Example
  7. Bean Definition Inheritance in Spring
  8. Input Splits in Hadoop