Java NIO - Path and Files handling using java nio package


Java NIO is a new package introduced in jdk 7, this provide extensive support for the file and file system management, learn about path and files in java nio, this will help you interact with file systems.

Files are a core of every software or program, every programming language gives a support for the file management and handling, Java is no exception. Java has created a new package in its core package library to handle the file operations. Up to jdk 6 the file handling concepts were all in java.io package, these are there up to some limit. But Java developers decided to create extended support for the file management. Java has introduced java.nio package in JDK 7. This is special package dedicated to file operation to separate the file operations from byte and character streams related operations.

This package support the file management to the basic level. If you try and explore this you will find that this is more than only the file handling but the support for the various platforms and different file system support has also been provided here. Most of the utility methods here are actually the static methods to ease your work.

Path

The concept of files start from the Path class. The path is of two types, Relative and Absolute. The Absolute path is the part starting from the root. and Relative is the path relative to any directory up to specified file or directory. As in the example the path from root to the file is a Absolute path

Java NIO path

/dir1/dir1.1/file - Absolute path

but if you try to access the file from current directory and the current directory is dir1 then,

dir1/dir1.1/file - Relative path

So Java provide an Interface Path and a final class Paths to take care of the paths in your program you can check out this interface on your console using command,

javap java.nio.file.Path
javap java.nio.file.Paths

The symbolic link means the link to a file or directory in different path, this is what we know as short cut link in general terms.

After looking into the methods provided in Path and Paths you can move on to the File system. However the general method we are going to use is Paths.get(URI);

Files

Files are the collection of data encoded on the storage media. There are different type of files and file systems. The file systems are the programs which manages the storage media and space on it. where the files are the elements which are stored on that media. the files have different properties and are identified using the extension which is usually three or four character long. The common file extensions are .txt for text files, .wmv, mp3, .amr for the audio files, .mp4, .flv, .mkv etc for the video files.

The extension helps a operating system to identify the file type which helps it to store it in a efficient way.

Now Java provide various ways to create and modify a file. Even the java.nio provide inbuilt methods to copy, move or delete the files on the file system. Java provide some enumerated options which comes in handy to specify the operation we want to do with the file, we use these options while opening a file.

These options are found in the java.nio.file.StandardOpenOptions most commonly used of these are,
WRITE - open file to write new data
APPEND - Append new data at the end of file
TRUNCATE_EXISTING - this is used when we are writing to a file, its operation is to truncate the data from file and make it empty.
CREATE_NEW - create new file, it throws exception if file is already existing, so you should first check the existence of file using exists() method.
CREATE - opens a file for writing, if file is not existing, create it and then open it.
DELETE_ON_CLOSE - delete the file when we close the file. This is used to create temporary files.
these are few main options however there are more you can find them in the StandardOpenOptions class.

Now let us look at the simplest way of creating the file. We use the Linux operating system for the programming purpose so the path we are going to use will be

/home//any-directory

where in windows you can use

C:\some-directory

Note: please take care that windows use the back slash for the directory specifier so you must make it like

Paths.get("C:\\some-directory");

the extra back slash is used to escape the backslash, because in java language specification the backslash is an escape character.

So lets not look at the program for copying a file content into another file. This will give you a basic idea of the file handling methods and practices. For example the IOException is the key exception thrown by any file operation on failing to fulfil any requirement. And you must close the resource handler on completing the task.


package IO;
import java.nio.file.*;
import java.io.*;
public class FileOperations {
    public static void main(String[] args) throws IOException{
        try{
        Path p = Paths.get("/home/mayank/test.txt");
        byte[] b = null;
        b = Files.readAllBytes(p);
        Path d = Paths.get("/home/mayank/test1.txt");
        Files.write(d, b,StandardOpenOption.APPEND);
        }
        catch(IOException ioe){
            System.out.println(ioe);
        }
    }
}

this program will take a file placed at /home/mayank/test.txt which contains some text for example, we put

hello world in the test file
new line in test file

in this file, and first of all we create a path for the file using the Path interface. You can test the existence of the path using Files.exists(p); method, this will return true on success and false if the path does not exists.

So this program when first time run will create a file test1.txt and will write the bytes read from test.txt which was read using the readAllBytes() method into the new file. But as you see the file test1.txt is opened with the StandardOpenOption.APPEND so when you next time run this file it will append the text at the end of the content in test1.txt.

Did you noticed we have not used finally to close any handlers ? yes there is no handlers in this program and please be careful this way of reading and writing is only applicable to the small files. For the files with bigger size you must use the Buffered Stream as we show in the following program.


import java.nio.file.*;
import java.nio.charset.Charset;
import java.io.*;

public class FileOperations {

    public static void main(String[] args) throws IOException {
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            Path p = Paths.get("/home/mayank/test.txt");
            br = Files.newBufferedReader(p, Charset.forName("UTF-8"));
            Path d = Paths.get("/home/mayank/test1.txt");
            bw = Files.newBufferedWriter(d, Charset.forName("UTF-8"));
            String s = null;
            while ((s = br.readLine()) != null) {
                bw.write(s);
            }
        } catch (IOException ioe) {
            System.out.println(ioe);
        } finally {
            if (br != null) {
                br.close();
            }
            if (bw != null) {
                bw.close();
            }
        }
    }
}

In this program we have used the buffered reader and writer to operate the streams while leaving the file handling to the new buffered reader and writer in the nio package. Now when you will run this program you will notice that the output in the test1.txt is all in one line, this is because in this program the reader is reading line by line but writer in just writing into the file, if you want the output file similar to the original file you can just change
bw.write(s) to bw.write(s+"\n");
this will give you the same result by appending the new line character to each line.

Note: As the file input output is better when you go with the character stream rather than the byte stream the nio gives you this flexibility while handling the underline byte stream by itself.

We hope you understand the tutorial, however if you want to learn using a video here is an excellent video tutorial for you.