更新时间:2023-09-19 21:14:16
您应该转换字符串
到字节[] 时指定字符集code>,反之亦然。
字节[]字节= string.getBytes(UTF-8);
//饲料字节为Base64
和
//从Base64编码字节
串串=新的字符串(字节,UTF-8);
否则该平台的默认编码将使用这不一定是UTF-8本身。
I'm using org.apache.commons.codec.binary.Base64 do decode string which is utf8. Sometimes I get base64 encoded string which after decode looks like for example ^@k��@@
. How can I check if base64 is correct or if decoded utf8 string is valid utf8 string?
To clarify. I'm using
public static String base64Decode(String str) {
try {
return new String(base64Decode(str.getBytes(Constants.UTF_8)), Constants.UTF_8);
} catch (UnsupportedEncodingException e) {
...
}
}
public static byte[] base64Decode(byte[] byteArray) {
return Base64.decodeBase64(byteArray);
}
You should specify the charset during converting String
to byte[]
and vice versa.
byte[] bytes = string.getBytes("UTF-8");
// feed bytes to Base64
and
// get bytes from Base64
String string = new String(bytes, "UTF-8");
Otherwise the platform default encoding will be used which is not necessarily UTF-8 per se.