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