Buffers store fixed amount of data. In technical terms, a
buffer can store fixed data of specific primitive type.
A Buffer can be stored in heap space of jvm, or off-heap
space of the jvm.
'java.nio.Buffer' is the abstract super class for all the
below primitive type buffers.
a.
ByteBuffer,
b.
CharBuffer,
c.
DoubleBuffer,
d.
FloatBuffer,
e.
IntBuffer,
f.
LongBuffer,
g.
ShortBuffer, and
h.
MappedByteBuffer
How to create a Buffer?
Buffer classes provide 'allocate' method to create buffer
instances.
Example
ByteBuffer buffer = ByteBuffer.allocate(1024);
CharBuffer charBuffer = CharBuffer.allocate(1024);
Key properties of
Buffer
capacity, limit and position are the essential properties
associated with the buffers.
a. capacity: It
represents the number of elements that a buffer can contain. This value never
changes through the life cycle. This value is set at the time of buffer
creation.
b. limit: It
specifies the index of the first element that should not be read or written. It
must not greater than the capacity. In simple terms, it represents the number
of live elements in the buffer.
c. position: it
specifies the index of the next element to be read (or) written. A buffer's
position is never negative and is never greater than its limit.
Let’s see an example of Buffer class, before digging
further.
testData.txt
If you can keep your head when all about you Are losing theirs and blaming it on you, If you can trust yourself when all men doubt you, But make allowance for their doubting too;
let’s see an example, how can we read the data using
ByteBuffer.
Step 1: Define an
instance of ByteBuffer.
ByteBuffer buffer = ByteBuffer.allocate(10);
Step 2: Get the
FileChannel instance from gien file path.
Path path = Paths.get(FILE_PATH);
FileChannel fileChannel = FileChannel.open(path);
Step 3: Read the
information from fileChannel to the buffer.
int noOfBytesRead = -1;
while ((noOfBytesRead = fileChannel.read(buffer)) != -1)
{
System.out.println(new
String(buffer.array()));
buffer.clear();
noOfBytesRead
= fileChannel.read(buffer);
}
Find the below working application.
Test.java
package com.sample.nio; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; public class Test { private static final String FILE_PATH = "C:\\Users\\krishna\\testData.txt"; public static void main(String args[]) throws Exception { /* Define new byte buffer of capacity 10 */ ByteBuffer buffer = ByteBuffer.allocate(10); /* Get FileChannel instance from the file */ Path path = Paths.get(FILE_PATH); try (FileChannel fileChannel = FileChannel.open(path)) { while ((fileChannel.read(buffer)) != -1) { System.out.println(new String(buffer.array())); buffer.clear(); } } } }
Output
If you can keep your head when all about you Are los ing theirs and blami ng it on y ou, If you can t rust yours elf when a ll men dou bt you, But mak e allowanc e for thei r doubting too; ng
No comments:
Post a Comment