What is the exact use of java nio package when already methods are available with io package
The main difference between IO and NIO is that IO is blocking, while NIO is non-blocking.
This article explains the differences in the packages and what blocking and non-blocking IO is. archived
Java programming, I/O has until recently been carried out using a stream metaphor. All I/O is viewed as the movement of single bytes, one at a time, through an object called a Stream. Stream I/O is used for contacting the outside world. It is also used internally, for turning objects into bytes and then back into objects.
NIO has the same role and purpose as original I/O, but it uses a different metaphor — block I/O. java.nio (new/non-blocking I/O) ) API was introduced with JDK1.4 .
What is difference between stream I/O and block I/O ?
A stream-oriented I/O system deals with data one byte at a time. An input stream produces one byte of data, and an output stream consumes one byte of data. It is very easy to create filters for streamed data. It is also relatively simply to chain several filters together so that each one does its part in what amounts to a single, sophisticated processing mechanism. On the flip side, stream-oriented I/O is often rather slow.
A block-oriented I/O system deals with data in blocks. Each operation produces or consumes a block of data in one step. Processing data by the block can be much faster than processing it by the (streamed) byte. But block-oriented I/O lacks some of the elegance and simplicity of stream-oriented I/O.
When you should use java.io and when should you prefer java.nio ?
Scalability will probably drive your choice of package. java.net will require one thread per socket. Coding it will be significantly easier. java.nio is much more efficient, but is difficult to code around.
You may get better scalability once you are dealing with tens of thousands of connections, but at lower numbers you’ll probably get better throughput with blocking IO.
When working with SSL java.nio is not some thing easy to deal with
Important : If you are working with either of the packages, it is not a good idea to create the framework from scratch until and unless you have a compelling reason to do so.
For java.nio , the projects such as Grizzly and Quick Server provide reusable non blocking server components.
Worth reading Pain points with java.nio
Finally it boils down to specific requirements of your projects and what you are trying to achieve. Some of the best solutions may not require the most complex infrastructure at al
Update : Recently found out about NIO.2 package which exists since jdk 1.7. NIO.2 is different than NIO, the major being that NIO.2 offers asynchronous channel functionality . NIO.2 primer
If you are working with NIO, worth going through the difference and which one suits your purpose.