I'm trying to create a bytebuffer of a specific size, create a
charbuffer view of that bytebuffer, and write a string into that
charbuffer. My bytebuffer always needs to be 4 bytes long (represent a
4 digit number), but no matter how I try to place some chars into the
buffer, I always get an overflow. For example:
//Test fixed length header strings
String ZeroString = "0000";
byte[] ByteSizeArray = ZeroString.getBytes();
int MessageHeaderSize = ByteSizeArray.length;
// int MessageHeaderSize = 4;
System.out.println("Length in bytes of 0000 = "+
MessageHeaderSize);
ByteBuffer HeaderBuffer =
ByteBuffer.allocateDirect(MessageHeaderSize);
System.out.println("HeaderBuffer.capacity() = "+
HeaderBuffer.capacity());
HeaderBuffer.put(ByteSizeArray);
StringBuffer HeaderStringBuffer = new StringBuffer(ZeroString);
CharBuffer HeaderCharBuffer = HeaderBuffer.asCharBuffer();
// Character ZeroChar = new Character("0");
for (int counter = 0; counter < HeaderBuffer.capacity();
counter++){
HeaderCharBuffer.put(counter, (char) 0);
}
Can someone tell me what I'm doing wrong here?
Thanks!
grasp06110@yahoo.com - 18 Apr 2006 13:58 GMT
Does the solution shown below work for you? It looks like the call to
headerBuffer.asCharBuffer(); was returning a zero capacity buffer. The
loop was using the capacity of the other buffer as a counter.
Therefore, the loop was entered (capacity of the other buffer was 4)
and an attempt was made to add data to the zero capacity buffer.
What IDE are you using? Eclipse has some nice debugging tools that
might have been helpful.
Hope this helps,
John
/**
*
*/
package com.mydomain.example;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
/**
* @author greshje
*
*/
public class Example {
public static void main(String[] args) throws Exception {
// Test fixed length header strings
String zeroString = "0000";
byte[] bytes = zeroString.getBytes();
int messageHeaderSize = bytes.length;
// int MessageHeaderSize = 4;
System.out.println("Length in bytes of 0000 = "
+ messageHeaderSize);
ByteBuffer headerBuffer =
ByteBuffer.allocateDirect(messageHeaderSize);
System.out.println("HeaderBuffer.capacity() = "
+ headerBuffer.capacity());
headerBuffer.put(bytes);
StringBuffer headerStringBuffer = new StringBuffer(zeroString);
// CharBuffer headerCharBuffer = headerBuffer.asCharBuffer();
CharBuffer headerCharBuffer = CharBuffer.allocate(4);
for (int counter = 0;
counter < headerCharBuffer.capacity();
counter++) {
System.out.println(counter);
headerCharBuffer.put(counter, (char) 0);
}
}
}
nooneinparticular314159@yahoo.com - 18 Apr 2006 14:39 GMT
Wow. Thanks! That makes sense. So basically, I need to be sure to
initialize the back end buffer, and what I was doing before didn't do
that. :)
I use Netbeans.