Java I/O(Input/Output) Overview

Java I/O(Input/Output) handles the task for getting data from a source or saving data to a target. Packages java.io and java.nio is used to handle I/O issues. In this topic we will give you a general overview about the two packages and introduce new features in java.nio.

All the classes included in java.io package is used to perform read or write actions using stream. The stream transfer byte data between program and source. Stream can only perform one-way transfer, that means you can only use inputstream to read from source and give the data back to program as well as outputstream to write to target from a program. Because there is only one byte was reading/writing from/to the input/output stream at one time so this type of operation is very slow.

Do not worry, the java.nio package introduce buffer and channel concept to solve low speed issue exist in stream based I/O.
Channel represents a connection between a program and data source like stream. But the difference between channel and stream is that channel can transfer data in two direction. Channel can be used to write to target as well as read from source. There has 3 channel types. They are read-only, write-only and read-write.

Buffer is used as a data container with fixed capacity, the capacity of buffer determines maximum number of data it can contain.
Data is written into buffer in channel based I/O class. When the buffer is full, it will be delivered to channel and channel write the data to target. When retrieving data from a source, we give the channel a buffer object. The channel reads data into the buffer object then we can use the data in it. This is quite different from stream based I/O which read/write data from/to stream directly.

Java 7 add three new package for the library: java.nio.file, java.nio.file.spi and java.nio.file.attribute.
These packages add following new features.
1. Use a uniform way to handles all file systems.
2. Symbolic links support .
3. Supports fundamental file treatments (move, copy, and delete) in all file systems.
4. Supports for getting attributes of files.
5. Introduce watch service that can watch any events occured on file or directory(create file or a subdirectory,  copy files or trash a file, etc).

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.