Chander Shivdasani
Chander Shivdasani

Reputation: 10121

Stream oriented IO vs Block Oriented IO

Java has stream oriented IO(java.io.) and Block oriented IO(java.nio.). How does block oriented IO improve the performance of IO?

Upvotes: 2

Views: 3395

Answers (3)

pardeep131085
pardeep131085

Reputation: 5518

The stream-based I/O uses streams to transfer data between a data source/sink and a Java program. The Java program reads from or writes to a stream a byte at a time. This approach to performing I/O operations is slow. The New Input/Ouput (NIO) solves the slow speed problem in the older stream-based I/O.

enter image description here

In NIO, you deal with channels and buffers for I/O operations.

A channel is like a stream. It represents a connection between a data source/sink and a Java program for data transfer.

enter image description here

There is one difference between a channel and a stream.

  • A stream can be used for one-way data transfer. That is, an input stream can only transfer data from a data source to a Java program; an output stream can only transfer data from a Java program to a data sink.
  • However, a channel provides a two-way data transfer facility.

You can use a channel to read data as well as to write data. You can obtain a read-only channel, a write-only channel, or a read-write channel depending on your needs.

Upvotes: 6

Rahul Tripathi
Rahul Tripathi

Reputation: 172408

From the Source:-

IO vs. NIO

NIO construction makes I/O faster than traditional I/O. In a program where the I/O operations constitute a significant amount of the processing, expect to see some difference. For example if an application has to copy files or transfer bytes using sockets, using Nio is possible to obtain a faster performance because it is closer to the OS than the I/O API. Increasing the byte size, the difference becomes more appreciable. Nio also provides other features not in io API, for streaming operations. However, it is not possible to substitute IO with NIO because NIO API adds functionalities to the java.io. NIO extends the native IO API introducing new possibilities for the developer to manipulate stream data in a powerful way.

Upvotes: 2

Primarily by reducing the need for copying. Since the stream-oriented APIs have to move everything into managed Java variables, the system has to copy all of the data you deal with. When you use the NIO libraries, Java can directly map in the OS I/O pages without having to make copies (and deal with allocation and garbage collection).

Upvotes: 7

Related Questions