Java8 comes with a great Files API. Doing anything with folders and files are much easier than ever. You don’t have to use the File object packed with package. Let’s take a look at that Files API in JAVA 8 with some examples.

Creating a File with Files API in JAVA 8

Files API has a static method called createFile. You just pass a Paths object with the filename in it.

Get File’s AbsolutePath

You can use Paths object to get the absolute path of a file.

Check File Exist or Not

Create Directory

You can use Files API to create a folder by using the static createDirectory method.

Then you can create a File under it.

Delete Directory or File

Write to a File

We create a DemoFolder and then create a text file. Then append some text inside of it.

Copy File to Another Folder

Get Line Count of File

Those commands are mostly the basic stuff that you would need in any project. But there is advanced stuff to explore in the new Files API in JAVA 8. Here is some of them.

Search for a File under a Directory

This is a tricky operation as there might be parent-child relation between folders and you need to look every folder to find your file. For this operation, you need to implement walkFileTree. This method will look over all the folders under the rootPath that you provide. You need to provide a signal to terminate the search operation in case the file is found. There are many signals that you can send like CONTINUE, SKIP_SUBTREE etc…

In this operation, the search will start from the directory located under SourceFolder. Files will be matches the file name that we search for. In case it’s not a match, we send a CONTINUE signal, in case the file is found we send the TERMINATE signal.