Close

Java IO & NIO - Files.createDirectory() Examples

Java IO & NIO Java Java API 


Class:

java.nio.file.Files

java.lang.Objectjava.lang.Objectjava.nio.file.Filesjava.nio.file.FilesLogicBig

Method:

public static Path createDirectory(Path dir,
                                   FileAttribute<?>... attrs)
                            throws IOException

Creates a new directory. The check for the existence of the file and the creation of the directory if it does not exist are atomic operations. This method throws FileAlreadyExistsException if the directory already exits. Files#createDirectories() method should be used where it is required to create all nonexistent parent directories first.

Parameters:
dir - the directory to create
attrs - an optional list of file attributes to set atomically when creating the directory
Returns:
the directory


Examples


package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateDirectoryExample {

public static void main(String... args) throws IOException {
Path tempPath = Files.createTempDirectory("test");
Path dirToCreate = tempPath.resolve("test1");
System.out.println("dir to create: " + dirToCreate);
System.out.println("dir exits: " + Files.exists(dirToCreate));
//creating directory
Path directory = Files.createDirectory(dirToCreate);
System.out.println("directory created: " + directory);
System.out.println("dir created exits: " + Files.exists(directory));
}
}

Output

dir to create: C:\Users\Joe\AppData\Local\Temp\test17538061336291321171\test1
dir exits: false
directory created: C:\Users\Joe\AppData\Local\Temp\test17538061336291321171\test1
dir created exits: true




package com.logicbig.example.files;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class CreateDirectoryExample2 {

public static void main(String... args) throws IOException {
Path tempPath = Files.createTempDirectory("test");
Path dirToCreate = tempPath.resolve("test1");
//creating directory
Files.createDirectory(dirToCreate);
//creating the same directory one more time will throw exception
Files.createDirectory(dirToCreate);
}
}

Output

Caused by: java.nio.file.FileAlreadyExistsException: C:\Users\Joe\AppData\Local\Temp\test370666579946134434\test1
at java.base/sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:87)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:103)
at java.base/sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:108)
at java.base/sun.nio.fs.WindowsFileSystemProvider.createDirectory(WindowsFileSystemProvider.java:505)
at java.base/java.nio.file.Files.createDirectory(Files.java:682)
at com.logicbig.example.files.CreateDirectoryExample2.main(CreateDirectoryExample2.java:21)
... 6 more




See Also