How to detect the failure of byte[] => String conversion

  • Thread starter Sakagami Hiroki
  • Start date
S

Sakagami Hiroki

Hi,

When I want to convert a byte array to a String object, I can use
String constructor with charset parameter:

String result = new String(bytearray, charset);

Here, if the bytearray contains any illegal sequence of bytes in
charset, they seems to be replaced with `?'. Is it possible to throw
Exception instead of using replacement characters?

Regards,
 
T

Timo Stamm

Sakagami said:
Hi,

When I want to convert a byte array to a String object, I can use
String constructor with charset parameter:

String result = new String(bytearray, charset);

Here, if the bytearray contains any illegal sequence of bytes in
charset, they seems to be replaced with `?'. Is it possible to throw
Exception instead of using replacement characters?

Not using the String class. The String class uses the Charset and
CharsetDecoder classes and you can do so too:

CharsetDecoder d = Charset.forName("US-ASCII").newDecoder();
try {
CharBuffer r = d.decode(ByteBuffer.wrap(bytearray));
r.toString(); // your encoded String
} catch(CharacterCodingException e) {
// ...
}


Timo
 
S

Sakagami Hiroki

Timo said:
Not using the String class. The String class uses the Charset and
CharsetDecoder classes and you can do so too:

CharsetDecoder d = Charset.forName("US-ASCII").newDecoder();
try {
CharBuffer r = d.decode(ByteBuffer.wrap(bytearray));
r.toString(); // your encoded String
} catch(CharacterCodingException e) {
// ...
}

Works fine. Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,773
Messages
2,569,594
Members
45,123
Latest member
Layne6498
Top