Powered by Blogger.

Tuesday 19 May 2015

Parts of NIO System

No comments :
There are three parts of NIO (New Input Output) System.
1. Using NIO for channel-based I/O.
2. Using NIO for Stream-based I/O.
3. Using NIO for path and File System Operations.


Using NIO for Channel-Based I/O
An important use of NIO is to access a file via a channel and buffers. The Following sections demonstrate some techniques that use a channel to read from and write to a file.
Reading a File Via a Channel : There are several way to read dat from a file using a channel. Perhaps the most common way is to manually allocate a buffer and then perform an explicit read operation than loads that buffer with data from the file. It is with this approach that we begin.
Before you can read from a file, you must open it. To do This first create a Path that describes the file. Then use this Path to open the file. There are various ways to open the file depending on how it will be used. In this Example, the file will be opened for byte-based input via explicit input operations. Therefore, This Example will open the file and establish a channel to it by calling Files.newByteChannel(). The newByteChannel() method has this general form:



It returns a SeekableBytehannel object, which encapsulations the channel for file operations. The Path that describes the file is passed in path. The how parameter specifies how the file will be opened. Because it is a Varargas  parameter, you can specify zero or more comma separated arguments. if no arguments are specified, the file is opened for input operations. SeekableByteChannel is an interface that describes a channel that can be used for file operations. It is implemented by the FileChannel class. when the default file system is used, the returned object can be cast to FileChannel. you must close the channel after you have finished with it. Since all Channels, including FileChannel, implement AutoCloseable, you can use a try- with-resources statement to close the file automatically instead of calling close() explicitly. This approach is used in the example.
Next, you must obtain a buffer that will be used by the channel either by wrapping an existing array or by allocating the buffer dynamically. The examples use allocation, but the choice is yours. Because file channels operate on byte buffers, we will use the allocate() method defined by ByteBuffer to obtain the buffer. It has this general form:
static ByteBuffer allocate(int cap)
Here, cap specifies the capacity of the buffer. A reference to the buffer is returned.  

Tuesday 24 March 2015

Java Exploting NIO Technology

No comments :
Java Exploring NIO
Java has provided a second I/O system called NIO (which is short for “New Input Output” or “New I/O”). It supports a buffer-oriented, Channel based Approach to I/O operations. The NIO system was greatly expanded, providing enhanced support for file-handling and file system features. The NIO Classes: The NIO classes are contained in the packages shown here.
Package
Purpose
Java.nio
Tope level package for the NIO System. Encapsulation Various types of buffers that contain data operated upon by the NIO system. 
java.nio.channel
Supports channels, which are essentially open I/O Connection.
Java.nio.channels.spi
Supports service providers for channels.
Java.nio.charset
Encapsulation character set. Also supports encoders and decoders that convert characters to bytes and bytes to character, respectively.
Java.nio.charset.spi
Supports service providers for character set.
Java.nio.file
Provides supports for file
Java.nio.file.attribute
Provides supports for file attributes.
Java.nio.file.spi
Supports service provider for file system
It is important to emphasize that the NIO subsystem does not replace the stream-based I/O classes found in java.io, and good working knowledge of the stream-based I/O in java.io is helpful to understanding NIO. NIO Fundamentals: The NIO system is built on two foundational items: buffers and channels. A buffer holds data. A channel represents an open connection to I/O devices, such as a file or a socket. In general, to use the NIO system, you obtain a channel to an I/O device and a buffer to hold data. You then operate on the buffer, inputting or outputting data as needed. The following sections examine buffers and channels in more detail. Buffers: Buffers are defined in the java.nio package. All buffers are subclasses of the buffer class, which defines the core functionality common to all buffers: current position, limit and capacity. The current position is the index within the buffer at which the next read or write operation will take place. The current position is advanced by most read or write operations. The limit is the index value one part of lest valid location in the buffer. The capacity is the number of elements that the buffer can hold. Often the limit equals the capacity of the buffer. Buffer also supports mark and rest. Buffer defines several methods, which are show in table.
Method
Description
abstract Object array()
If the invoking buffer is backed by an array, returns a reference to the array. Otherwise, an UnsupportedOperationException is thrown. If the array is read-only, a ReadOnlyBufferException is thrown.
abstract int arrayOffset()
If the invoking buffer is blocked by an array, returns the index of the first element. Otherwise, an UnsupportedOperationException is thrown. If the array is read-only, a ReadOnlyBufferException is thrown.
final int capacity()
Returns the number of elements that the invoking buffer is capable of holding.
final Buffer clear()
Clear the invoking buffer and returns a reference to the buffer.
final Buffer flip()
Sets the invoking buffer’s limit to the current position and resets the current position to 0. Returns a reference to the buffer.
abstract boolean hasArray() 
Returns true if the invoking buffer is backed by a read/write array and false otherwise.
abstract boolean hasRemaining() 
Returns true if there are elements remaining in the invoking buffer. Returns false otherwise.
abstract boolean isDirect()
Returns true if the invoking buffer is direct, which means I/O operation act directly upon it. Returns false otherwise.
abstract boolen isReadOnly()
Returns true if the invoking butter is read-only. Returns false otherwise.
finial int limit()
Returns the invoking buffer’s limit.
finial Buffer limit(int n)
Sets the invoking buffer’s limit to n. Returns a reference to the buffer.
finial Buffer mark()
Sets the mark and returns a reference to the invoking buffer.
finial int position()
Returns the current position.
finial Buffer position(int n)
Sets the invoking buffer’s current position to n. Returns a reference to the buffer.
Int remaining()
Returns the number of elements available before the limit is reached. “or” It returns the limit minus the current position.
finial Buffer reset()
Returns the current position of the invoking buffer to the previously set mark. Returns a reference to the buffer.
finial Buffer rewind() 
Sets the position of the invoking buffer to 0. Returns a reference to the buffer.
From Buffer, the following specific buffer classes are derived, which is hold the type of data that their names imply:
ByteBuffer
CharBuffer
DoubleBuffer
FloatBuffer
IntBuffer
LongBuffer
MappedByteBuffer
ShortBuffer
MappedByteBuffer is a subclass of the byteBuffer and is used to map a file to buffer. All of the aforementioned buffers provide various get() and put() methods, which allow to get data from a buffer or put data into a buffer. (If a buffer is read-only, then put() operations are not allow.) The other buffer classes have similar methods. All buffer classes also support a method that performs variable buffer operations. For example, you can allocate a buffer manually using allocate(). You can wrap an array inside a buffer using wrap(). You can create a subsequence of a buffer using slice().
Channels:
Channels are defined in java.nio.channel. A channel represents an open connection to an I/O source or destination. Channels implement the channel interface. It extends Closeable, and it extends AutoCloseable. By implementing AutoCloseable , channel can be managed.
Method
Description
abstract byte get()
Returns the byte at the current position.
ByteBuffer get(byte vals[])
Copies the invoking buffer into the array referred to the vals. Returns the reference to the buffer, a not vals. Length elements remaining in the buffer, a BufferUnderflowException is through.
ByteBuffer get(byte vals[], int start, int num)
Copies num elements from the invoking buffer into the array referred to by vals, beginning at the index specified by start. Returns a reference to the buffer. If there are not num elements remaining in the buffer, a BufferUnderflowException.
abstract byte get(int idx)
Returns the byte at the index specified by idx within the invoking buffer.
abstract ByteBuffer put(byte b)
Copies b into the invoking buffer at the current position. Returns a reference to the buffer. If the buffer is full, a BufferOverflowException is thrown.
Final ByteBuffer put(byte  vals[])
Copies all elements of vals into the invoking buffer, beginning at the current position. Returns a reference to the buffer. If the buffer cannot hold all of the elements, a BufferOverflowException.
ByteBuffer put(byte vals[], int start, int num)
Copies num elements from vals, beginning ta start, into the invoking buffer. Returns a reference to the buffer. If the buffer cannot hold all of the elements, a BufferOverflowException.
ByteBuffer put(ByteBuffer bb)
Copies the elements in bb to the invoking buffer, beginning at the current position. If the buffer cannot hold all elements, a BufferOverflowException  is thrown. Returns a reference to the buffer.
abstract ByteBuffer put(int  idx, byte b)
Copies b into the invoking buffer at the location specified by idx. Returns a reference to the buffer.
Note: The get() and put() Methods defined for ByteBuffer. One way to obtain a channel is by calling getChannel() on an object that supports channel. For example , getChannel() is supported by the following I/O classes:
DatagramSocket
FileInputStream
FileOutputStream
RandomAccessFile
ServerSocket
Socket
The specific type of channel returned depends upon the type of object getChannel() is called on. For example, when called on a FileInputStream, FileOutputStream, or RandomAccessFile, getChannel() returns a channel of type FileChannel. When called on a Socket, getChannel. Another way to obtain a channel is to use one of the static methods defined by the Files class. For Example, using Files, you can obtain a byte channel by calling newByteChannel() . It returns a SeekabaleByteChannel, which is an interface implemented by FileChannel. Channels such as FileChannel and SocketChannel support various read() and write() Methods that enable you to perform I/O operations throw the channel .
For example, here are a few of the read() and write() methods defined for FileChannel.
Method
Description
abstract int read(ByteBuffer bb)throws IOException
Reads bytes from the invoking channel into bb until the buffer are full or there is no more input. Returns the number of bytes actually read. Returns -1 at end-of-stream.
abstract int read(ByteBuffer bb, long start)throws IOException
Beginning at the location specified by start, reads bytes form the invoking channel into bb unit the buffer is full or there is no more input. The current position is unchanged. Returns the number of bytes actually read or -1 if start is beyond the end of the file.
abstract int write(ByteBuffer bb)throws IOException 
Write the contents of bb to the invoking channel, starting at the current position. Returns the number of bytes written.
abstract int write(ByteBuffer bb, long start)throws IOException
Beginning at the file location specified by start, writes the contents of bb to the invoking channel. The current position is unchanged. Returns the number of bytes written.
All channels support additional methods that give you access to and control over the channel. For example, FileChannel supports methods to get or set the current position, transfer information between file channels, obtain the current size of channel, and lock the channel, among other. FileChannel provides a static method called open(), which opens a file and returns a channel to it. This provides another way to obtain channel. FileChannel Also provides the map() method, which lets you map a file to a buffer.