开发者

Handle byte[] with ByteBuffer

开发者 https://www.devze.com 2023-02-04 11:20 出处:网络
I try to access a byte[] via a ByteBuffer in order to represent a file-type I defined. The first positions within the byte[] contain some Metadata and get treated with bit-manipulations. So they开发者

I try to access a byte[] via a ByteBuffer in order to represent a file-type I defined. The first positions within the byte[] contain some Metadata and get treated with bit-manipulations. So they开发者_如何学C do not represent a char at all.

I want to add file-data (chars e. g.) at a certain fixed position.

byte[] file_portion contains a portion of a large file: the beginning section. Which includes the header with the Metadata. content is a String with information I want to add to that buffer. start_pos is the first position to hold the new file-data from content.

ByteBuffer my_content = ByteBuffer.allocate(this.file_portion.length);
content_buffer.wrap(this.file_portion);

for (int i = 0; i < content.length(); i++) {
    char tmp = content.toCharArray()[i];
    my_content.put(this.start_pos + i, (byte) tmp)
}

If I remap this I get a garbage and emptyness:

CharBuffer debug = my_content.asCharBuffer();
System.out.println("debug " + debug);

I could understand if the first positions show corrupted chars... but not a single one position is correct.


If you are adding chars to a ByteBuffer and expecting them to be readable with a CharBuffer view, you should be using putChar(...) not put(...).

EDITED: per OP comments.

For example:

char[] chars = content.toCharArray();  // removed from loop per leonbloy's excellent comment  
CharBuffer cbuf = my_content.asCharBuffer();

for (int i = 0; i < content.length(); i++) {
    cbuf.putChar(chars[i]);
}

CharBuffer debug = my_content.asCharBuffer();
System.out.println(debug);

my_content.position(my_content.position() + 2*chars.length);

Otherwise the CharBuffer is reading two of your consecutive bytes as a single char. Now the cbuf buffer will start loading chars at the same point your byte buffer left off. After loading all of the chars, your original ByteBuffer will be positioned to the next location. Hopefully this is what you're looking for.


Are you aware that in Java a char occupies two bytes?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号