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

ByteBuffergetReadBuffer(File file)
get Read Buffer
try (RandomAccessFile f = new RandomAccessFile(file, "r")) {
    return f.getChannel().map(MapMode.READ_ONLY, 0, file.length());
} catch (IOException e) {
    return null;
StringgetStringContents(ReadableByteChannel channel)
Gets String contents from channel and closes it.
try {
    ByteBuffer buffer = ByteBuffer.allocate(1024 * 8);
    StringBuilder sb = new StringBuilder();
    int bytesRead = channel.read(buffer);
    while (bytesRead != -1) {
        buffer.flip();
        CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer);
        sb.append(charBuffer.toString());
...
byte[]largeFileReader(String filename)
good for Large Files >2Mb
byte[] bytes = null;
FileChannel fc = null;
try {
    fc = new FileInputStream(filename).getChannel();
    MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    int size = byteBuffer.capacity();
    if (size > 0) {
        byteBuffer.clear();
...
ByteBuffermapReadWrite(File file)
This is a convenience method for mapping an entire File into a ByteBuffer .
return mapReadWrite(file, 0, file.length());
voidnioCopy(ReadableByteChannel input, WritableByteChannel output)
nio Copy
try {
    ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
    while (input.read(buffer) != -1) {
        buffer.flip();
        output.write(buffer);
        buffer.compact();
    buffer.flip();
...
MappedByteBufferopenReadOnly(Path path, int offset, int length)
Maps a portion of a file to memory and returns the mapped read-only byte buffer using the given offset and length.
try (FileChannel fc = FileChannel.open(path, READ)) {
    return fc.map(READ_ONLY, offset, truncateLength(fc, length));
ByteBufferread(DataInput in, int length)
read
if (length == 0)
    return EMPTY_BYTE_BUFFER;
byte[] buff = new byte[length];
in.readFully(buff);
return ByteBuffer.wrap(buff);
Stringread(File file)
read
return _collect(file.toPath(), _UTF_8);
Stringread(File file)
read
return new String(readBytes(file), UTF8);
ByteBufferread(File file, long offset, int length)
read
FileChannel chan = channel(file, false);
ByteBuffer buf = ByteBuffer.allocate(length);
chan.position(offset);
while (buf.remaining() > 0) {
    if (chan.read(buf) <= 0) {
        throw new IOException("Failed to read from channel.");
buf.rewind();
chan.close();
return buf;