Understand Path, Paths and Files in Java NIO
Jun 27, 2020
Make sure to subscribe to our newsletter and be the first to know the news.
Jun 27, 2020
Make sure to subscribe to our newsletter and be the first to know the news.
Java NIO (New Input Output) comes with following utility classes
A Path represents a path that is hierarchical and composed of a sequence of directory and file name elements separated by a special separator or delimiter
This class consists exclusively of static methods that return a Path by converting a path string or URI
This class consists exclusively of static methods that operate on files, directories, or other types of files.
To locate a Path we use the static method get() of Paths class which returns the Path object which is then passed to Files methods to start the operation.
For Example to Create a Directory Following Block of the Code is required
Path p=Paths.get("D:\\Code With Z\\New Folder");
Path path=Files.createDirectory(p);
Paths convert the path fed in String/URI and generate a Path object for it, an later the same Path object is passed to the static method of Files.
Some of the important methods of Files class are as follows
Method (all methods are static) | Returns | Description |
File Operations | ||
---|---|---|
createDirectory(Path dir, FileAttribute ... attrs) | Path | Creates a new directory. |
createFile(Path path, FileAttribute ... attrs) | Path | Creates a new and empty file, failing if the file already exists. |
delete(Path path) | boolean | Deletes a file. |
copy(Path source, Path target, CopyOption...options) | Path | Copy a File to a target file |
list(Path dir) | Stream | Return a lazily populated Stream, the elements of which are the entries in the directory. |
move(Path source, Path target, CopyOption ...options) | Path | Move or rename a file to a target file. |
File Details | ||
isExecutable(Path path) | boolean | Tests whether a file is executable. |
isHidden(Path path) | booelan | Tells whether or not a file is considered hidden. |
isReadable(Path path) | booelan | Tests whether a file is readable. |
exists(Path path, LinkOption... option) | booelan | Tests whether a file exists. |
notExists(Path path, LinkOption ... option) | booelan | Tests whether the file located by this path does not exist. |
size(Path path) | long | Returns the size of a file (in bytes). |
Reading and Writing Operations | ||
readAllLines(Path path) | List | Read all lines from a file. |
readAllBytes(Path path) | byte[ ] | Reads all the bytes from a file. |
write(Path path, byte[ ] bytes, OpenOption... options) | Path | Writes bytes to a file. |
write(Path path, Iterable lines, OpenOption... options) | Path | Write lines of text to a file. |
So these are the methods available with Files class which we will be making use in the further tutorials for the Files management.