简体   繁体   中英

Buffer Marking in Java NIO

I'm having an issue regarding the marking function of the Buffer class from the Java NIO API. I'm trying to run some examples using a ByteBuffer, which inherits the marking functionality from the Buffer parent class.

The example I want to achieve is having "AwesomeSauce" as an output first followed by "Sauce", using the marking functionality. The code is below:

public class MarkingNIO {

public static void main(String[] args) {
    ByteBuffer buffer = ByteBuffer.allocate(20);
    byte byteArray[];

    buffer.put("AwesomeSauce".getBytes());

    int prevPos = buffer.position();
    buffer.position(7).mark().position(prevPos); //Mark position 7 and revert back so that we can flip
    buffer.flip();

    byteArray = new byte[buffer.limit() - buffer.position()];

    for (int i = 0; buffer.hasRemaining(); i++) {
        byteArray[i] = buffer.get();
    }

    System.out.println("Whole string: " + new String(byteArray));

    buffer.reset();

    byteArray = new byte[buffer.limit() - buffer.position()];

    for (int i = 0; buffer.hasRemaining(); i++) {
        byteArray[i] = buffer.get();
    }

    System.out.println("Partial String" + new String(byteArray));
}
}

The output for me is as follows:

AwesomeSauce
Exception in thread "main" java.nio.InvalidMarkException
    at java.nio.Buffer.reset(Buffer.java:306)
    at markingnio.MarkingNIO.main(MarkingNIO.java:37)
Java Result: 1

The error points to the reset method.

EDIT: I did this to test out the mark() and reset() methods for learning purposes. Either way, the problem was that the flip() method had a statement of "mark = -1", and the position(int) had a statement of "if (mark > position) mark = -1;"

look at this line:

buffer.flip();
public final Buffer flip() {
    limit = position;
    position = 0;
    mark = -1;
    return this;
}

this call will set mark=-1, and see implements of method reset():

public final Buffer reset() {
    int m = mark;
    if (m < 0)
        throw new InvalidMarkException();
    position = m;
    return this;
}

the reset will throw InvalidMarkException while mark=-1;

you can delete the: buffer.position(7).mark().position(prevPos); ,and change the buffer.reset(); into buffer.position(7);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM