Introduction to Java NIO
The NIO ("New I/O") package1 was introduced in Java 1.4 to get round certain
limitations of the original Java I/O package. The main features of NIO are:
- buffers: the java.io package
had essentially focussed on stream-based I/O;
it is often fiddly to "read a block of data and then process it as a block";
- memory-mapped files: on a related point, the java.io package did not provide file mapping, a
feature offered by modern operating systems in which part of a file is effectively "mapped" into
memory and accessed as though it were memory— see the section on mapped
ByteBuffers for more details;
- readiness selection: when managing concurrent network connections (and indeed,
concurrently open streams in general), the traditional I/O package
focussed on the conventional way of managing those connections, in which
each connection is handled by a separate thread; modern operating
systems provide more efficient methods, including readiness selection,
in which one thread can poll and handle a number of connections;
- direct transfer of data within kernel memory space:
pre-NIO, stream data had to be manipulated at the Java level so that, for example,
transferring data from one stream to another had to involve spurious buffer copying from the
OS into Java and then back again; NIO, via the new concept of channels, provides a method to conveniently transfer data between files/media in Java;
- locking: the standard I/O package did not deal with file locking
(or, more broadly, concurrent access to parts of a file) explicitly.
Since Java 7, the NIO API has been complemented with the NIO2 API. This plugs certain
gaps in Java's I/O handling such as dealing properly with file attributes and symbolic links.
It also provides simpler API calls for performing certain common operations such as reading and writing
data to file. See the Files class for more information.
1. You're possibly wondering how to pronounce NIO.
All I can tell you is that I've heard Sun employees pronounce it both en-eye-oh
and nigh-oh, and I've heard other colleagues pronounce it nee-oh.
Pick the one you prefer.
If you enjoy this Java programming article, please share with friends and colleagues. Follow the author on Twitter for the latest news and rants.
Editorial page content written by Neil Coffey. Copyright © Javamex UK 2021. All rights reserved.