开发者

Filechannel position and string length

In Java chars are 2 bytes long, But when I write a string to a file using a bytebuffer the filechannel position increments by the number of chars. I read that the Filechannel.position() method returns the number of bytes from the beginning of the file to the current positi开发者_如何学Con so shoudnt it increment by 2*numberof chars?.


In Java chars are 2 bytes long

Inside the JVM. When written out they can be 1-4 bytes long depending on the character set.

But when I write a string to a file using a bytebuffer the filechannel position increments by the number of chars.

No, it increments by the number of bytes.

I read that the Filechannel.position() method returns the number of bytes from the beginning of the file to the current position so shoudnt it increment by 2*numberof chars?

No. Your question is founded on two fallacies.


Not quite. In Java, the char type is twice the bit width of the byte type, but that only means chars can be two bytes long. It depends on your String's character encoding, but with UTF-8 encoding (the default), chars are encoded as only one byte for chars between 0 and 127, but multiple bytes for chars over this range (when the high bit is set, it means the next byte is also part of the current char)

For Strings made of only 0-127 characters (ie "normal text"), byte length will equal char length.

If your String contains characters outside the range 0-127, byte length will be greater than the number of characters.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜