Advanced IO in JAVA


nio pacjage has so many new features for reading and writing in files and sockets. It is major upgrade over age old java.io package. 

  • ·       Capture Events, It capture the changes happening in files, like save, updates.
  • ·       Asynchronous operations It can read and write to files in non blocking mode, via Selectors.

Let’s understand building blocks of this package.

Buffer: Buffer class represents block of memory used for storing data. It has few interesting feature, The one I liked was flip . its toggle to read or write from or to buffer.Here are list of few buffer types

  • ·        Byte Buffer
  • ·        Char Buffer

File Channel. File channel is basic block. this works both ways, that is read and write both from buffer. See the small code example of File Channel and Buffer.File Channel Opens a stream and writes into buffer.

aFile = new RandomAccessFile(filename, "rw");

FileChannel inChannel = aFile.getChannel();

is = Channels.newInputStream(inChannel);

bufferedReader = new BufferedReader(new InputStreamReader(is));

ByteBuffer buf = ByteBuffer.allocate(48);

int bytesRead = inChannel.read(buf);

buf.flip();

while(buf.hasRemaining()){

   System.out.print((char) buf.get());

}

see the use of flip() method. First channel writes into buffer, we can control the buffer size up to last byte of memory.After flipping the buffer, it starts reading from buffer.

Watch Service for capturing events in Files

A watch service that watches registered objects for changes and events. For example, a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.

Here is small code example to monitor directory. This will monitor modify events in directory

WatchService watchService= FileSystems.getDefault().newWatchService();

 Path path = Paths.get(System.getProperty("user.home"));

 path.register(

          watchService,

                StandardWatchEventKinds.ENTRY_MODIFY);

  WatchKey key;

        while ((key = watchService.take()) != null) {

            for (WatchEvent<?> event : key.pollEvents()) {

                System.out.println(

                  "Event kind:" + event.kind()

                    + ". File affected: " + event.context() + ".");

            }

            key.reset();

Watch key class represents the registration of a directory with the watch service. Its instance is returned to us by the watch service when we register a directory and when we ask the watch service if any events, we registered for have occurred.

My personal experience with using watcher service was little exhaustive. I used Watcher service to watch excel file. I found there are more than one events generated for one update. One has to experiment to identify the right event and ignore rest.

Asynchronous Reading By Selector

A selector is for monitoring events on channel. A selector may be created by invoking the open method of this class. Next is to register channel with Selector. One important point is however, blocking channel can not be registered with Selector, so File channel can not be registered with Selector.

There are four event that can be registered with selectors.

  • Read
  • Write
  • Connect
  • Accept

A channel that "fires an event" is also said to be "ready" for that event. So, a channel that has connected successfully to another server is "connect ready". A server socket channel which accepts an incoming connection is "accept" ready. A channel that has data ready to be read is "read" ready. A channel that is ready for you to write data to it, is "write" ready.

With help of Selector and events, channels can be handled in asynchronous way.

Hope you will use Java nio package in your next project

To view or add a comment, sign in

More articles by Kapil Shukla

  • Developing Chat Feature with Claude API.

    Most people will agree Talking or Chatting is most human like behavior, Where Humans feel natural and at ease. That is…

  • BMTC Bus and Office journey in Bangalore

    Bangalore traffic is perpetual topic of discussion. It is indeed difficult to manoeuvre every day twice.

  • Spring AI and Semantic Search. Part two

    The difference between semantic search and keyword search is, keyword search returns results that match words to words,…

    4 Comments
  • Spring AI- Java arrives in AI development- Part one.

    Spring Boot is Java based Framework, popular among Java developer across Globe for quick development of Prod Grade…

    1 Comment
  • Certifications

    Certifications!!! In IT, where technology explosion is happening at a very rapid pace, the pressure to remain updated…

    2 Comments
  • How to crack an Interview

    In the past couple of months, It have been interviweing lots of java candidate for various positions in my company…

    9 Comments
  • Net working in Azure

    Once we decide to move our on-premises’ networks, hardware etc to Azure. First thing to create will be network in azure…

  • Active Directory in Azure

    Azure active directory (AAD) is multi-tenant cloud-based directory and identity management system. AAD is platform as…

  • Kubernetes in Azure

    Kubernetes(K8s) is container-orchestration system for automating deployment, scaling, and management of containerized…

    2 Comments
  • Monitoring in Azure

    Monitoring in Azure Azure is famous cloud solution from Microsoft, commanding second largest market share only behind…

Others also viewed

Explore content categories