Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Introduction

In this tutorial, we’ll cover Java IO functionalities and how they changed throughout different Java versions. First, we’ll cover the java.io package from the initial Java version. Next, we’ll go over java.nio package introduced in Java 1.4. In the end, we’ll cover the java.nio.file package, commonly known as the NIO.2 package.

2. Java NIO Package

The first Java version was released with the java.io package, introducing a File class to access the file system. The File class represents files and directories and provides limited operations on the file system. It was possible to create and delete files, check if they exist, check read/write access, etc.

It also has some shortcomings:

  • Lack of copy method – to copy a file, we need to create two File instances and use a buffer to read from one and write to another File instance.
  • Bad error handling  – some methods return boolean as an indicator if an operation is successful or not.
  • A limited set of file attributes – name, path, read/write privileges, memory size is available, to name a few.
  • Blocking API – our thread is blocked until the IO operation is complete.

To read a file, we need a FileInputStream instance to read bytes from the file:

@Test
public void readFromFileUsingFileIO() throws Exception {
    File file = new File("src/test/resources/nio-vs-nio2.txt");
    FileInputStream in = new FileInputStream(file);
    StringBuilder content = new StringBuilder();
    int data = in.read();
    while (data != -1) {
        content.append((char) data);
        data = in.read();
    }
    in.close();
    assertThat(content.toString()).isEqualTo("Hello from file!");
}

Next, Java 1.4 introduces non-blocking IO API bundled in java.nio package (nio stands for new IO). NIO was introduced to overcome the limitations of the java.io package. This package introduced three core classes: Channel, Buffer, and Selector.

2.1. Channel

Java NIO Channel is a class that allows us to read and write to a buffer. Channel class is similar to Streams (here we speak of IO Streams, not Java 1.8 Streams) with a couple of differences. Channel is a two-way street while Streams are usually one-way, and they can read and write asynchronously.

There are couple implementations of the Channel class, including FileChannel for file system read/write, DatagramChannel for read/write over a network using UDP, and SocketChannel for read/write over a network using TCP.

2.2. Buffer

Buffer is a block of memory from which we can read or write data into it. NIO Buffer object wraps a memory block. Buffer class provides a set of functionalities to work with the memory block. To work with Buffer objects, we need to understand three major properties of the Buffer class: capacity, position, and limit.

  • Capacity defines the size of the memory block. When we write data to the buffer, we can write only a limited length. When the buffer is full, we need to read the data or clear it.
  • The position is the starting point where we write our data. An empty buffer starts from 0 and goes to capacity – 1. Also, when we read the data, we start from the position value.
  • Limit means how we can write and read from the buffer.

There are multiple variations of the Buffer class. One for each primitive Java type, excluding the Boolean type plus the MappedByteBuffer.

To work with a buffer, we need to know a few important methods:

  • allocate(int value) – we use this method to create a buffer of a certain size.
  • flip() – this method is used to switch from write to read mode
  • clear() – method for clearing the content of the buffer
  • compact() – method for clearing only the content we have already read
  • rewind() – resets position back to 0 so we can reread the data in the buffer

Using previously described concepts, let’s use Channel and Buffer classes to read content from file:

@Test
public void readFromFileUsingFileChannel() throws Exception {
    RandomAccessFile file = new RandomAccessFile("src/test/resources/nio-vs-nio2.txt", "r");
    FileChannel channel = file.getChannel();
    StringBuilder content = new StringBuilder();
    ByteBuffer buffer = ByteBuffer.allocate(256);
    int bytesRead = channel.read(buffer);
    while (bytesRead != -1) {
        buffer.flip();
        while (buffer.hasRemaining()) {
            content.append((char) buffer.get());
        }
        buffer.clear();
        bytesRead = channel.read(buffer);
    }
    file.close();
    assertThat(content.toString()).isEqualTo("Hello from file!");
}

After initializing all required objects, we read from the channel into the buffer. Next, in the while loop, we mark the buffer for reading using the flip() method and read one byte at a time, and append it to our result. In the end, we clear the data and read another batch.

2.3. Selector

Java NIO Selector allows us to manage multiple channels with a single thread. To use a selector object to monitor multiple channels, each channel instance must be in the non-blocking mode, and we must register it. After channel registration, we get a SelectionKey object representing the connection between channel and selector. When we have multiple channels connected to a selector, we can use the select() method to check how many channels are ready for use. After calling the select() method, we can use selectedKeys() method to fetch all ready channels.

2.4. Shortcomings of NIO Package

The changes java.nio package introduced is more related to low-level data IO. While they allowed non-blocking API, other aspects remained problematic:

  • Limited support for symbolic links
  • Limited support for file attributes access
  • Missing better file system management tools

3. Java NIO.2 Package

Java 1.7 introduces new java.nio.file package, also known as NIO.2 package. This package follows an asynchronous approach to non-blocking IO not supported in java.nio package. The most significant changes are related to high-level file manipulation. They are added with Files, Path, and Paths classes. The most notable low-level change is the addition of AsynchroniousFileChannel and AsyncroniousSocketChannel.

Path object represents a hierarchical sequence of directories and file names separated by a delimiter. The root component is furthest to the left, while the file is right. This class provides utility methods such as getFileName(), getParent(), etc. The Path class also provides resolve and relativize methods that help construct paths between different files. Paths class is a set of static utility methods that receive String or URI to create Path instances.

Files class provides utility methods that use the previously described Path class and operate on files, directories, and symbolic links. It also provides a way to read many file attributes using readAttributes() method.

In the end, let’s see how NIO.2 compares to previous IO versions when it comes to reading a file:

@Test
public void readFromFileUsingNIO2() throws Exception {
    List<String> strings = Files.readAllLines(Paths.get("src/test/resources/nio-vs-nio2.txt"));
    assertThat(strings.get(0)).isEqualTo("Hello from file!");
}

4. Conclusion

In this article, we covered the basics of java.nio and java.nio.file packages. As we can see, NIO.2 is not the new version of the NIO package. The NIO package introduced a low-level API for non-blocking IO, while NIO.2 introduced better file management. These two packages are not synonymous, rather a compliment to each other. As always, all code samples can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are closed on this article!