Home » Java programming language

Java File Class static File createTempFile(String file_name, String file_extension) method with Example

Java File Class static File createTempFile(String file_name, String file_extension) method: Here, we are going to learn about the static File createTempFile(String file_name, String file_extension) method of File class with its syntax and example.
Submitted by Preeti Jain, on July 14, 2019

File Class static File createTempFile(String file_name, String file_extension)

  • This method is available in package java.io.File.createTempFile(String file_name , String file_extension).
  • This method is used to create a temporary file in a specified directory and if the directory is not given then default directory will get selected.
  • This method is static so it will be accessible with classname.

Syntax:

    static File createTempFile(String file_name , String file_extension){
    }

Parameter(s):

We pass two objects as a parameter in the method of the File i.e file_name and file_extension. So the first argument is filename and the second argument is file extension so if the file extension is null then it takes default extension is '.tmp'.

Return value:

The return type of this method is File. So, it returns a temporary file.

Java program to demonstrate example of createTempFile() method

// import the File class because we will use File class methods
import java.io.File;

// import the Exception class because it may raise an 
// exception when working with files
import java.lang.Exception;

public class CreateTempFile {
    public static void main(String[] args) {
        try {
            // Specify the path of file and we use double slashes to 
            // escape '\' character sequence for windows otherwise 
            // it will be considerable as url.

            // create a temporary file object 
            File file = File.createTempFile("Java", ".txt");

            // check whether file exists or not
            if (file.exists()) {
                // Temporary file will create in current directory with named 
                // Java and extension is .txt so the filename will be Java.txt
                System.out.println("Temp File created: " + file.getName());
            } else {
                // if the file is not created
                System.out.println("Temp File cannot be created: " + file.getName());
            }
        } catch (Exception e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }
}

Output

E:\Programs>javac CreateTempFile.java

E:\Programs>java CreateTempFile
Temp File created: Java5580937140195842517.txt


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.