wishi
wishi

Reputation: 7387

Handle byte[] with ByteBuffer

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 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.

Upvotes: 0

Views: 2270

Answers (2)

robert_x44
robert_x44

Reputation: 9314

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.

Upvotes: 2

leonbloy
leonbloy

Reputation: 75896

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

Upvotes: 2

Related Questions