kamaci kamaci - 4 months ago 15
Java Question

Setting Charset for String

I use forbiddenapis to check my code. It gives an error:

[forbiddenapis] Forbidden class/interface use: java.lang.String#<init>(byte[])
[forbiddenapis] in org.a.b.MyObject (MyObject.java:14)


Which points to:

String finalString = new String(((ByteArrayOutputStream) out).toByteArray());


How can I resolve it? I know that I can set a Charset, i.e.:

Charset.forName("UTF-8").encode(myString);


However since there is used byte, which charset should I use to avoid a problem with different characters?

Answer

Do not use FileReader. This is an old utility class to read files in the default platform encoding. That is not suited for portable files. The code is unportable.

String / Reader / Writer holds Unicode. When converting from byte[] / InputStream / OutputStream one needs to indicate the encoding of those bytes, binary data.

String s = new String(bytes, charset);
byte[] bytes = s.getBytes(charset);

It seems that the message mentions FileReader and complains about its

new String(bytes);

which uses the default encoding, as would:

string.getBytes();