New ByteBuffer with Shifted Bytes (Java)?
I have a ByteBuffer called buffer. I want to generate a new buffer that contains all of it's bytes that go from buffer.position() to the end of buffer followed by all of the bytes from position 0 to buffer.position()-1.
Essentially, I want to shift the bytes at the current position to the beginning of the buffer while bringing the current beginning to the end.
To illustrate, if this is my ByteBuffer (where P
is the current position and the numbers 0-9
indicate byte positions):
|0123456789|
P
... then I would want to form a new ByteBuffer that looks like this:
|3456789012|
P
Here's what I'm trying so far (and is not working):
ByteBuffer tmpByteBuffer = buffer.slice();
tmpByteBuffer.limit(buffer.capacity());
And here is the error (this is from LogCat on Android - although I don't think the issue is Android-specific):
12-22 03:49:44.303: ERROR/AndroidRuntime(10399): Uncaught handler: thread Thread-11 exiting due to uncaught exception
12-22 03:49:44.313: ERROR/AndroidRuntime(10399): java.lang.IllegalArgumentException
12-22 03:49:44.313: ERROR/AndroidRuntime(10399): at java.nio.Buffer.limit(Buffer.java:239)
12-22 03:49:44.313: ERROR/AndroidRuntime(10399): at com.chaimp.audiolistener.AudioListener.captureSamples(AudioListener.java:175)
12-22 03:49:44.313: ERROR/AndroidRuntime(10399): at com.chaimp.precisiontuner.PrecisionTuner$1.run(PrecisionTuner.java:28)
12-22 03:49:44.313: ERROR/AndroidRuntime(10399): at java.lang.Thread.r开发者_开发技巧un(Thread.java:1096)
Can anybody tell me what I'm doing wrong?
And, is there a better way to do this?
Thank you for any help with this.
Hm, I don't understand why do you need to set a limit on the sliced buffer. This should work:
ByteBuffer originalBuffer = getOriginalBuffer();
ByteBuffer newBuffer = ByteBuffer.allocate(originalBuffer.limit());
ByteBuffer slicedBuffer = originalBuffer.slice(); //Will be from pos to end
originalBuffer.flip(); //Will be from 0 to pos
newBuffer.put(slicedBuffer)
newBuffer.put(originalBuffer)
精彩评论