How to create temporary file in Java?

  • Create a temporary file with createTempFile(prefix, suffix);
package com.nourit.javaIO;

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

public class CreateTemporaryFile {

  public static void main(String[] args) {
    try {
      // create a temp file createTempFile(prefix, suffix)
      File temp = File.createTempFile("temp-nourit-file-name", ".tmp");
      System.out.println("Temporary file : " + temp.getAbsolutePath());

    } catch (IOException e) {

      e.printStackTrace();

    }
  }

}

Output:

Temporary file : C:\Users\Nour-it\AppData\Local\Temp\temp-nourit-file-name7293506289544648196.tmp
  • Create a temporary file with createTempFile(prefix, suffix,, File file);
package com.nourit.javaIO;

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

public class CreateTemporaryFile {

  public static void main(String[] args) {
    try {
      // create a temp file createTempFile(prefix, suffix, File file) -> suffix= .txt....
      File temp = File.createTempFile("temp-nourit-file-name", ".tmp", new File("D:/tmp/"));
      System.out.println("Temporary file : " + temp.getAbsolutePath());

    } catch (IOException e) {

      e.printStackTrace();

    }
  }

}

Output:

Temporary file : D:\tmp\temp-nourit-file-name7880135018657413763.tmp

 

NOUR-IT

IT Training Center for Java and Web technology. If you enjoy and like our tutorials and believe in our mission, Please Subscribe us on Youtube and follow us on Twitter, or befriend us on Facebook or Google Plus.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.

*