Java - File Input Output Create Directory


The createDirectory() and createDirectories() methods create a new directory.

If the parent directory of the new directory does not exist, the createDirectory() method fails.

The createDirectories() method creates a non-existent parent directory.

You can use the createTempDirectory() and createTempFile() methods to create a temporary directory and a temporary file respectively.

The following code creates temporary files and directories.


import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    try {//from  w  w w .  j ava2  s  .c  o  m
      String dirPrefix = "KDir";
      Path tDir = Files.createTempDirectory(dirPrefix);
      System.out.println("Temp directory: " + tDir);
      String fPrefix = "KF_";
      String fSuffix = ".txt";
      Path tFile1 = Files.createTempFile(fPrefix, fSuffix);
      System.out.println("Temp file1: " + tFile1);

      Path p1 = Paths.get("C:\\temp");
      Path tFile2 = Files.createTempFile(p1, fPrefix, fSuffix);
      System.out.println("Temp file2: " + tFile2);
    } catch (IOException e) {