How to transfer data from ByteBuffer to byte array in java.
In this tutorial you will see how to transfer data from ByteBuffer to byte array in java.
In this tutorial you will see how to transfer data from ByteBuffer to byte array in java.
How to transfer data from ByteBuffer to byte array in java.
In this tutorial, we will discuss the use of get(byte[] array,int offset, int
length) method of byte
stream class.
The get(byte[] array,int offset, int
length) method transfer bytes from buffer into byte array.
About ByteBuffer API:
The java.nio.ByteBuffer class extends java.nio.Buffer class.
It provides the following methods:
Return type |
Method |
Description |
static ByteBuffer |
wrap(byte array) |
The wrap method create a byte buffer by wrapping the associated byte array. |
ByteBuffer |
get(byte dest,int offset, int length) |
The get(.....) method transfer byte from associated buffer
into byte array. |
code
import java.io.*;
import java.nio.*;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class BufferTransfer {
public static void main(String[] args) throws Exception {
FileInputStream finStream = new FileInputStream("testfile1.txt");
byte[] bArray = new byte[125];
FileChannel fchannel = finStream.getChannel();
ByteBuffer bytebuf = ByteBuffer.wrap(bArray);
fchannel.read(bytebuf);
bytebuf.flip();
bArray = new byte[bytebuf.capacity()];
System.out.print("Contents into buffer : ");
while (bytebuf.hasRemaining()) {
System.out.print((char) bytebuf.get());
}
bytebuf.clear();
bytebuf.get(bArray, 0, bArray.length);
System.out.print("\n");
System.out.print("Contents into Array : ");
for (int i = 0; i < bytebuf.capacity(); i++) {
System.out.print((char) bArray[i]);
}
}
} |
output
C:\>java BufferTransfer
Contents into buffer : bharat singh
Contents into Array : bharat singh |
Download this code