Java Utililty Methods File Read via ByteBuffer

List of utility methods to do File Read via ByteBuffer

Description

The list of methods to do File Read via ByteBuffer are organized into topic(s).

Method

ByteBufferreadShortByteArray(DataInput in)
read Short Byte Array
int length = readShortLength(in);
ByteBuffer bb = ByteBuffer.allocate(length);
in.readFully(bb.array(), bb.position(), bb.remaining());
return bb;
StringreadString(ByteArrayInputStream bin)
read String
int length = readInt(bin);
if (length == -1)
    return null;
if (length == 0)
    return "";
byte[] buffer = new byte[length];
bin.read(buffer);
return new String(buffer, ENCODING);
...
StringreadString(ReadableByteChannel channel)
read String
int nameLen = readInt(channel); 
if (nameLen < 0) {
    return null;
ByteBuffer buf = ByteBuffer.allocate(nameLen * 2);
if (fillBuffer(channel, buf, true)) {
    char[] name = new char[nameLen];
    buf.rewind();
...
StringreadStringFromFile(String path)
Reads entire contents of specified file as a string.
File file = new File(path);
byte[] encoded = new byte[(int) file.length()];
DataInputStream ds = null;
try {
    ds = new DataInputStream(new FileInputStream(file));
    ds.readFully(encoded);
} finally {
    if (ds != null) {
...
StringreadStringFromSocketChannel(SocketChannel sc)
read String From Socket Channel
if (!sc.isOpen())
    return "";
StringBuffer resultString = new StringBuffer();
resultString.setLength(0);
ByteBuffer bbuf = ByteBuffer.allocate(BSIZE);
bbuf.clear();
try {
    int loopCounter = 0;
...
StringreadStringInUTF8(DataInput in)
read String In UTF
int allocationBlockSize = 2000;
int capacity = allocationBlockSize;
int length = 0;
ByteBuffer buffer = ByteBuffer.allocate(allocationBlockSize);
boolean notEof = true;
while (notEof) {
    try {
        buffer.put(in.readByte());
...
ByteBufferreadToBuffer(final String filename)
Get byte buffer from file path.
final File file = new File(filename);
final ByteBuffer bytebBuffer = ByteBuffer.allocate((int) file.length());
final FileInputStream fis = new FileInputStream(filename);
bytebBuffer.rewind();
int b = 0;
final byte[] buf = new byte[1024];
while ((b = fis.read()) != -1) {
    bytebBuffer.put((byte) b);
...
byte[]readToByteArray(String fname)
read a file into a byte array.
File f = new File(fname);
long l = f.length();
FileInputStream fs = new FileInputStream(fname);
FileChannel fc = fs.getChannel();
ByteBuffer dst = ByteBuffer.allocate((int) l);
fc.read(dst);
byte b[] = dst.array();
fc.close();
...
intreadTwoByteInt(byte[] array, int start)
read Two Byte Int
return ((array[start] & 255) << 8) + (array[start + 1] & 255);
StringreadTxtFromFile(File file)
read Txt From File
ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
FileInputStream in = new FileInputStream(file);
in.getChannel().read(buffer);
in.close();
return new String(buffer.array());