ADVERTISEMENT
ADVERTISEMENT

Create temporary file in specified directory in Java

Creating temporary file in a directory: Here, we are going to learn how to create temporary file in specified directory in Java?
Submitted by IncludeHelp, on July 19, 2019

The task is to create a temporary file in a specified directory.

To create a temporary file or to create a temporary file in a specified directory we use createTempFile() method. In the first case, we use two parameters (file name and extension), and, in the second case, we use three parameters (file name, extension name and specified directory).

Package to use: import java.io.*;

Syntax:

    // file object creation with directory name (path)
    File tempFile = new File("E://Java");

    // creating temporary file in specified directory
    File.createTempFile("JavaTemp", ".javatemp", tempFile);

Java code to create temporary file in specified directory

// Java code to create temporary file 
// in specified directory

import java.io.*;

public class CreateTempFileinDIR {
  public static void main(String[] args) {
    // file object to store the result
    File result = null;

    // file object creation with directory
    // name (path)
    File tempFile = new File("E://Java");

    try {
      // creating temporary file in specified directory
      result = File.createTempFile("JavaTemp", ".javatemp", tempFile);
    } catch (IOException exp) {
      System.out.println("Error in creating temporary file : " + exp);
    }
    // printing the created file path 
    System.out.println("Temporary file created at : " + tempFile.getPath());
  }
}

Output

E:\Programs>javac CreateTempFileinDIR.java

E:\Programs>java CreateTempFileinDIR
Temporary file created at : E:\Java

Java Files & Directories Programs »


ADVERTISEMENT




ADVERTISEMENT


Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.