Found reliance on default encoding

痴心易碎 提交于 2020-01-22 04:56:48

问题


I am getting below bug from FindBugs,

Found reliance on default encoding in MyClass.print(String): String.getBytes()

Method

protected void print (String str) {
{
private OutputStream outStream = null;
.....
outStream.write(str.getBytes());
.......
}

Please let me know what is the error? how we can resolve this?

Thanks in advance


回答1:


There are different ways of encoding a String as bytes -- the charset determines that encoding. If you don't specify a charset, as in your call to str.getBytes(), it uses the system default.

FindBugs is warning you about this because you should think about what encoding you want to use for your output. If you're writing to a file, what are the readers of that file expecting? It is safest if you can specify an explicit encoding for the file so you don't write it one way and read it another way.

To specify an explicit charset, use str.getBytes(Charset.forName("UTF-8")), for example. UTF-8 is a good choice because it is always supported and can encode any character.

For example, .properties files are always ISO 8859-1 (i.e. Latin-1). That's documented so there is no ambiguity around what encoding to use.



来源:https://stackoverflow.com/questions/10347435/found-reliance-on-default-encoding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!