Java IO & NIO - Files.createDirectories() Examples

Code Snippets Java IO & NIO Java 


Class:

java.nio.file.Files

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

Method:

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

Creates a directory by creating all nonexistent parent directories first. Unlike the Files#createDirectory method, an exception is not thrown if the directory could not be created because it already exists.

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


Examples


package com.logicbig.example.files;

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

public class CreateDirectoriesExample {

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

Output

dir to create: C:\Users\Joe\AppData\Local\Temp\test14242197814930499355\test1\test2
dir exits: false
directories created: C:\Users\Joe\AppData\Local\Temp\test14242197814930499355\test1\test2
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 CreateDirectoriesExample2 {

public static void main(String... args) throws IOException {
Path tempPath = Files.createTempDirectory("test");
Path dirToCreate = tempPath.resolve("test1").resolve("test2");
System.out.println("dir to create: " + dirToCreate);
System.out.println("dir exits: " + Files.exists(dirToCreate));
//creating directories
Path directories = Files.createDirectories(dirToCreate);
System.out.println("directories created: " + directories);
System.out.println("dir created exits: " + Files.exists(directories));
//creating same directories more times does not throw exception
Path directories1 = Files.createDirectories(directories);
System.out.println("second time directories: "+directories1);
}
}

Output

dir to create: C:\Users\Joe\AppData\Local\Temp\test3693387466625737258\test1\test2
dir exits: false
directories created: C:\Users\Joe\AppData\Local\Temp\test3693387466625737258\test1\test2
dir created exits: true
second time directories: C:\Users\Joe\AppData\Local\Temp\test3693387466625737258\test1\test2




See Also