Java java.nio.file.Files createDirectory()Method
java.nio.file.Files.createDirectory()is a utility method in the Java NIO (New I/O) package for creating a new directory. It belongs tojava.nio.file.Filesutility class, providing a simple and safe way to create a single directory.
Method Definition
Parameter Description
dir: The path of the directory to be created (Path object)attrs(Optional): An optional list of FileAttribute for setting directory attributes (such as permissions)
Return Value
Returns the Path object of the created directory
Exceptions
IOException: If an I/O error occursFileAlreadyExistsException: If the directory already existsSecurityException: If there is insufficient permission to create the directory
Basic Usage Example
Example
public class CreateDirectoryExample {
public static void main(String[] args) {
Path path = Paths.get("C:/test/new_directory");
try {
Files.createDirectory(path);
System.out.println("Directory created successfully: " + path);
} catch (IOException e) {
System.err.println("Failed to create directory: " + e.getMessage());
}
}
}
Method Characteristics
1. Create a Single Directory
createDirectory()Can only create a single directory. If the parent directory in the path does not exist, it will throwNoSuchFileException。
2. Atomic Operation
Directory creation is an atomic operation; it either completely succeeds or completely fails.
3. Directory Existence Check
If the directory already exists, the method will throwFileAlreadyExistsException。
Difference from createDirectories()
FilesThe class also providescreateDirectories()method. The main differences between the two are:
| Feature | createDirectory() | createDirectories() |
|---|---|---|
| Create a single directory | Yes | Yes |
| Create multi-level directories | no | Yes |
| When the parent directory does not exist | Throws an exception | Automatically creates parent directories |
| When the directory already exists | Throws an exception | Does not throw an exception |
Advanced Usage
1. Setting Directory Attributes
Example
import java.nio.file.attribute.PosixFilePermission;
import java.util.Set;
Path path = Paths.get("/path/to/new_directory");
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
Files.createDirectory(path, attr);
2. Handling Exceptions
Example
Files.createDirectory(path);
} catch (FileAlreadyExistsException e) {
System.err.println("Directory already exists: " + path);
} catch (NoSuchFileException e) {
System.err.println("Parent directory does not exist: " + e.getFile());
} catch (IOException e) {
System.err.println("Other I/O error: " + e.getMessage());
}
Best Practices
- Check if the directory exists: Before attempting to create, you can use
Files.exists(path)to check - Handle all possible exceptions: especially
FileAlreadyExistsExceptionandNoSuchFileException - **Consider using createDirectories()**: If you need to create multi-level directories
- Set appropriate permissions: especially in multi-user systems
Summary
Files.createDirectory()is the recommended method in Java NIO for creating a single directory. It providesFile.mkdir()richer functionality and better exception handling. Understanding this method and itscreateDirectories()difference, which can help developers handle file system operations more effectively.
Java java.nio.file.Files