Hidden Java pitfalls

Written by: | Posted on:

The kind of errors I hate the most are the ones you cannot even find in the documentation. When you get no compiler warnings, and even an incentive from your preferred auto-completion tool to go straight into them.

Todays such error is the following:

byte[] buffer = /* something that fills the buffer with the contents of a string*/;<br /> String stringBuffer = new String(buffer, Charset.forName("UTF8"));

What's wrong here?? Compiles fine, looks fine.... let's read the doc... fine. Except, as it turns out, for long buffers, it will truncate the string and add a trailing .... So you need to do something like this instead

String stringBuffer = new String(buffer, 0, lengthOfBuffer, Charset.forName("UTF8"));

That gives you a correct string, not truncated and not with a ... at the end. *sigh*

Image Image

Father, husband, software developer, musician and photographer.


Get to know what I'm up to

© 2020 Niklas Saers Contact Me