How to Create Temp File or Directory in Java

By How to Create Temp File or Directory in Java
This tutorial shows how to create temp file and temp directory using java

Create Temp Directory in Java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class TempDirectory{
    public static void main(String[] args) {
        try {
            Path tempDirPath = Files.createTempDirectory("tempDir");
            System.out.println("Temporary folder created at "+ tempDirPath);
        } catch (IOException ex) {
            System.out.println("I/O error:"+ ex.getLocalizedMessage());
             ex.printStackTrace();
        }
    }
}

Create Temp File in Java

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class TempFile {
    public static void main(String[] args) {
        try {
            Path tempFilePath = Files.createTempFile("tempFile", ".txt");
            System.out.println("Temp file created at "+ tempFilePath);
        } catch (IOException ex) {
            System.out.println("I/O error:"+ ex.getLocalizedMessage());
             ex.printStackTrace();
        }
    }
}
Was this article helpful?
Donate with PayPal: https://www.paypal.com/donate

Bessy
Eric Murithi Muchenah

Life is beautiful, time is precious. Make the most out of it.