Whenever you read from or write to the buffer, only it's position changes.

So you are wrong about reading from channel. Note that reading from channel means writing to the buffer. You can set the position to 0 and limit - to the maximum number of bytes to read before you call Channel.read(ByteBuffer). The read operation then updates the position to the number of bytes actually read. So, to start reading from buffer you have to call ByteBuffer.flip().

Answer from lorus on Stack Exchange
🌐
GeeksforGeeks
geeksforgeeks.org › java › bytebuffer-position-methods-in-java-with-examples
ByteBuffer position() methods in Java with Examples - GeeksforGeeks
June 27, 2019 - // Java program to demonstrate // position() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(4); // try to set the position at index 1 // using position() method bb.position(1); // putting the value of ByteBuffer // using put() method bb.put((byte)10); // try to set the position at index 3 // using position() method bb.position(3); // putting the value of ByteBuffer // using put() method bb.put((byte)30); // display position System.out.println("ByteBuffer: " + Arrays.toString(bb.array())); } }
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › nio › ByteBuffer.html
ByteBuffer (Java Platform SE 7 )
Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four. ... Absolute get method for reading an int value. Reads four bytes at the given index, composing them into a int value according to ...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › nio › ByteBuffer.html
ByteBuffer (Java Platform SE 8 )
July 21, 2026 - Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four. ... Absolute get method for reading an int value. Reads four bytes at the given index, composing them into a int value according to ...
🌐
Oracle
docs.oracle.com › javase › 9 › docs › api › java › nio › ByteBuffer.html
ByteBuffer (Java SE 9 & JDK 9 )
Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four. ... Absolute get method for reading an int value. Reads four bytes at the given index, composing them into a int value according to ...
🌐
Baeldung
baeldung.com › home › java › java io › guide to bytebuffer
Guide to ByteBuffer | Baeldung
November 28, 2024 - There are four indices defined in the ByteBuffer class. These indices record the state of the underlying data elements: Capacity: the maximum number of data elements the buffer can hold ... It’s worth noting that position, limit, and capacity won’t be negative.
🌐
HappyCoders.eu
happycoders.eu › java › bytebuffer-flip-compact
Java ByteBuffer Example: How to use flip() + compact()
June 12, 2025 - The reading position is at the beginning of the buffer, to where the compact() method shifted the remaining 100 twos. So we can now continue reading at precisely the position where we stopped before.
Top answer
1 of 3
4

Your buffer is never filled. bytes.array() simply retrieves the backing byte array. If you write anything to this then the ByteBuffer fields - except the array itself of course - are unaffected. So the position stays at zero.

What you are doing in in.read(bytes.array()) is identical to byte[] tmp = bytes.array() followed by in.read(tmp). Changes to the tmp variable cannot be reflected in the bytes instance. The backing array is changed which may mean that the contents of the ByteBuffer is changed as well. But the offsets into the backing byte array - including the position and limit - aren't.

You should only fill the ByteBuffer using any of the put methods (that do not take an index) such as put(byte[]).


I'll provide a code fragment that may get you thinking on how to handle strings, encodings and character and byte buffers:

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.StandardCharsets;

public class TestBuffer {

    private static final String testStr = "Stackoverflow is a great place to discuss tech stuff!";
    private static final boolean END_OF_INPUT = true;

    private ByteBuffer bytes = ByteBuffer.allocate(1000);

    public TestBuffer() {

        System.out.println("init   : " + bytes.toString());
    }

    public static void main(String a[]) {
        TestBuffer buf = new TestBuffer();
        buf.writeBuffer();
        buf.readBuffer();
    }

    // write testStr to buffer
    private void writeBuffer() {
        CharBuffer testBuffer = CharBuffer.wrap(testStr);
        CharsetEncoder utf8Encoder = StandardCharsets.UTF_8.newEncoder();
        CoderResult result = utf8Encoder.encode(testBuffer, bytes, END_OF_INPUT);
        if (result.isError()) {
            bytes.clear();
            throw new IllegalArgumentException("That didn't go right because " + result.toString());
        }
        if (result.isOverflow()) {
            bytes.clear();
            throw new IllegalArgumentException("Well, too little buffer space.");
        }
        System.out.println("written: " + bytes.toString());
        bytes.flip();
    }

    // read buffer data back to byte array and print
    private void readBuffer() {
        byte[] b = new byte[bytes.remaining()];
        bytes.get(b);
        System.out.println("data   : " + new String(b, StandardCharsets.UTF_8));
        System.out.println("read   : " + bytes.toString());
        bytes.clear();
    }
}

Note that buffers and streams are really two separate ways of handling sequential data. If you are trying to use both of them at the same time you may be trying to be too clever.

You could also solve this without CharBuffer and ByteBuffer using a byte[] buffer and a StringReader wrapped by a ReaderInputStream.


That Android piece of code completely abuses the ByteBuffer. It should just have created a byte[] and wrapped that, setting the limit to the capacity. Whatever you do, do not use it as an example on ByteBuffer handling. It made my eyes water in disgust. Code like that is a bug waiting to happen.

2 of 3
1

You are not writting anything in the writeBuffer() method.

You may use something like bytes.put(b).

Find elsewhere
🌐
Tricentis
tabnine.com › home › products overview
Agentic Quality Engineering Platform - Tricentis
January 31, 2018 - AI writes code faster than teams can test it. Tricentis deploys a team of specialized AI agents, governed by AI Workspace, to test, validate, and release at AI speed.
Top answer
1 of 1
3

The ByteBuffer class offers absolute get operations which can access the value at any valid index. For instance, ByteBuffer#get(int) accepts an index and returns the byte at that index. It does this without mutating the position of the buffer, meaning your code won't have any side-effects. Here's an example which finds all indices of a single byte:

public static int[] allIndicesOf(ByteBuffer buf, byte b) {
  return IntStream.range(buf.position(), buf.limit())
      .filter(i -> buf.get(i) == b)
      .toArray();
}

This avoids copying the information into a byte[] and leaves the ByteBuffer in the same state as it was when given to the method. Also note that the buffer is only searched from its current position to its limit. If you want to search the entire buffer then use range(0, buf.capacity()).

Here's another example except this one allows you to search for a "sub-array" in the buffer:

public static int[] allIndicesOf(ByteBuffer buf, byte[] b) {
  if (b.length == 0) {
    return new int[0];
  }
  return IntStream.rangeClosed(buf.position(), buf.limit() - b.length)
      .filter(i -> IntStream.range(0, b.length).allMatch(j -> buf.get(i + j) == b[j]))
      .toArray();
}

The code works for getting the position. Is it possible if i just want to delete that ASCII char '10' when found in bytebuffer fro that byte buffer?

Here's an example of removing all occurrences of the specified byte:

public static void removeAll(ByteBuffer buf, byte b) {
  for (int i = buf.position(); i < buf.limit(); i++) {
    // find first occurrence
    if (buf.get(i) == b) {
      // copy every remaining byte which != 'b' over
      for (int j = i + 1; j < buf.limit(); j++) {
        if (buf.get(j) != b) {
          buf.put(i++, buf.get(j));
        }
      }
      // update limit of buffer (implicitly causes outer for loop to exit)
      buf.limit(i);
    }
  }
}
🌐
Android Developers
developer.android.com › api reference › bytebuffer
ByteBuffer | API reference | Android Developers
August 3, 2026 - Skip to main content · English · Deutsch · Español – América Latina · Français · Indonesia · Polski · Português – Brasil · Tiếng Việt · 中文 – 简体
🌐
Mindprod
mindprod.com › jgloss › bytebuffer.html
ByteBuffer : Java Glossary
The capacity indexes the first slot past the end of the buffer. When filling the buffer, the limit is the same as the capacity. When emptying the buffer, it is one past the last filled byte in the buffer. When filling the buffer, the position points just past the last byte filled in the buffer.
🌐
TutorialsPoint
tutorialspoint.com › bytebuffer-get-method-in-java
ByteBuffer get() method in Java
The value at the current position of the buffer is read and then incremented using the method get() in the class java.nio.ByteBuffer. This method returns the value that is at the current buffer position. Also, the BufferUnderflowException is throw
🌐
Gunnar Morling
morling.dev › blog › bytebuffer-and-the-dreaded-nosuchmethoderror
ByteBuffer and the Dreaded NoSuchMethodError - Gunnar Morling
When run on Java 1.8, this virtual method call will be resolved to Buffer#position(int) at runtime, whereas on Java 9 and later, it’d resolve to the bridge method inserted by the compiler into the class file of ByteBuffer due to the co-variant return type, which itself calls the overriding ByteBuffer#position(int) method.
🌐
GeeksforGeeks
geeksforgeeks.org › java › bytebuffer-reset-methods-in-java-with-examples
ByteBuffer reset() methods in Java with Examples - GeeksforGeeks
July 16, 2019 - // Java program to demonstrate // reset() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { try { byte[] barr = { 10, 20, 30, 40 }; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.wrap(barr); // try to set the position at index 2 bb.position(2); // Set this buffer mark position // using mark() method bb.mark(); // try to set the position at index 4 bb.position(1); // display position System.out.println("position before reset: " + bb.position()); // try to call reset() to restore // to the position we marked bb.reset(); // display position System.out.println("position after reset: " + bb.position()); } catch (InvalidMarkException e) { System.out.println("\nnew position is less than " + "the position we marked before "); System.out.println("Exception throws: " + e); } } }
🌐
Oracle
docs.oracle.com › en › java › javase › 14 › docs › api › java.base › java › nio › ByteBuffer.html
ByteBuffer (Java SE 14 & JDK 14)
Writes four bytes containing the given int value, in the current byte order, into this buffer at the current position, and then increments the position by four. ... Absolute get method for reading an int value. Reads four bytes at the given index, composing them into a int value according to ...