Java.io.File.createTempFile() Method

Advertisements


Description

The java.io.File.createTempFile(String prefix, String suffix, File directory) method creates a new empty file in the specified directory.

deleteOnExit() method is called to delete the file created by this method.

Declaration

Following is the declaration for java.io.File.createTempFile(String prefix, String suffix, File directory) method:

public static File createTempFile(String prefix, String suffix, File directory)

Parameters

  • prefix -- The prefix string defines the files name; must be at least three characters long

  • suffix -- The suffix string defines the file's extension; if null the suffix ".tmp" will be used

  • directory -- The directory in which the file is to be created. For default temporary-file directory null is to passed

Return Value

An abstract pathname for the newly-created empty file.

Exception

  • IllegalArgumentException -- If the prefix argument contains less than three characters

  • IOException -- If a file creation failed

  • SecurityException -- If SecurityManager.checkWrite(java.lang.String) method does not allow a file to be created

Example

The following example shows the usage of java.io.File.createTempFile(String prefix, String suffix, File directory) method.

package com.tutorialspoint;

import java.io.File;

public class FileDemo {
   public static void main(String[] args) {
      
      File f = null;
            
      try{
         // creates temporary file
         f = File.createTempFile("tmp", ".txt", new File("C:/"));
         
         // prints absolute path
         System.out.println("File path: "+f.getAbsolutePath());
         
         // deletes file when the virtual machine terminate
         f.deleteOnExit();
         
         // creates temporary file
         f = File.createTempFile("tmp", null, new File("D:/"));
         
         // prints absolute path
         System.out.print("File path: "+f.getAbsolutePath());
         
         // deletes file when the virtual machine terminate
         f.deleteOnExit();
         
      }catch(Exception e){
         // if any error occurs
         e.printStackTrace();
      }
   }
}

Let us compile and run the above program, this will produce the following result:

File path: C:\tmp3602253894598046604.txt
File path: D:\tmp587577452036748166.tmp



Advertisements
Advertisements