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.  

No comments :

Post a Comment

Please Write a Message for Programming or something Related issues.