Example of creating a directory or directories hierarchy using the Java NIO package classes. The Java nio package is used to write heavy I/O related and applications which gives optimum performance.
About Java NIO package
The NIO is also know as the the Non-blocking I/O or some time is also know as the "New I/O" is set of Java API for creating the intensive I/O operations oriented applications. It was first released with the JSE 1.4. NIO package was developed under the JSR 51. There is also an extension of the NIO, the NIO2 which is released with the Java SE 7.
Features of NIO:
Following are most noted features of the NIO package:
- NIO package provides the buffers for the primitive data types
- It also provides the character set encoders and decoders
- Perl-style regular expressions matching support is also provided
- It also introduced the Channels, a new primitive I/O abstraction
- It also provides the multiplexed, non-blocking I/O facility for writing scalable servers
How to create directory using the Java nio package?
The Files.createDirectory() method will be used to create directory using the nio package. Here is the complete code of creating a directory using the nio package classes:
import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.Path; public class NIOCreateDirectory { public static void main(String[] args) { System.out.println("Creating file using the nio package!"); Path dirPath = Paths.get("D:/examples/devmanuals/mydirectory"); try{ if (!Files.exists(dirPath)) { Files.createDirectory(dirPath); System.out.println("Directory Created"); } }catch(Exception e){ System.out.println("Error while Creating Directory:" + e.getMessage()); } } }
If you want to create directory and sub-directories then you should use the Files.createDirectories() method.
While performing any I/O operations you should always check the existence of the directory, file etc to avoid any runtime errors.
You may use the following methods:
- exists(Path path, LinkOption... options): This is used to check if file exists.
- isExecutable(Path path): With the help of this method you can find if a file is executable or not.
- isHidden(Path path): This is used to find if a path is hidden or not.
- isReadable(Path path): This function is used to find if a file is readable.
- isWritable(Path path): This method is used to find if a file is writable.
Read more Tutorials at File Handling in Java Tutorial Section.
[ 0 ] Comments