Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

Reading a String from ByteBuffer without double buffering

Is there a way to construct a String from ByteBuffer without first reading contents from the buffer to a intermediate byte[] or char[]?

An API similar to the string constructor that takes a byte[] strikes me as ideal:

public String(ByteBuffer buffer, int offset, int length, Charset charset)

... but no such thing exists.

I've found How to convert from ByteBuffer to Integer and String?, but it uses an auxiliary array.

I the next best thing I've found so far is to project the byte buffer as a CharBuffer and call toString(). But that doesn't allow for compressing the strings with something like UTF-8.

Upvotes: 3

Views: 3244

Answers (4)

gaborsch
gaborsch

Reputation: 15748

String is made of chars, not bytes. You would need a character set, which you use to convert the bytes to characters, e.g. UTF-8, UTF-16, ISO-8859-1, ISO-8859-5, ...

If you don't know the character set, you will not know which character the bytes represent.

Upvotes: 0

Affe
Affe

Reputation: 47954

java.lang.String is immutable and final, so there is ultimately no choice but to eventually provide data in a format it already accepts. (Short of manipulating its internals with reflection of course....)

You could hide the ugliness behind an API that uses string builder or something, but there will at some point be two copies of the array in memory, one in the builder and one for the actual string.

Upvotes: 1

user2030471
user2030471

Reputation:

What about CharsetDecoder.decode and calling toString on the returned CharBuffer.

Upvotes: 3

Simon G.
Simon G.

Reputation: 6707

There is no such thing.

A ByteBuffer does not contain characters. They have to be converted to characters before you can make a String out of them.

Also, a String has to be inside the JVM memory. A ByteBuffer may be mapped or direct, in both cases it is outside the JVM.

In order to move the data into the JVM and convert it to characters, you have to use an auxiliary array.

Upvotes: 1

Related Questions