问题描述
我正在解决FindBugs的错误,
I am getting below bug from FindBugs,
发现依赖MyClass.print(String)中的默认编码:String.getBytes()
Found reliance on default encoding in MyClass.print(String): String.getBytes()
方法
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?
预先感谢
推荐答案
将String编码为字节有多种方法-字符集确定该编码.如果您未指定字符集(如在调用str.getBytes()
时那样),它将使用系统默认值.
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向您发出警告,因为您应该考虑要对输出使用哪种编码.如果您正在写文件,那么该文件的读者会有什么期望?如果可以为文件指定显式编码,这样就最安全了,因此您不必以一种方式写入文件,而以另一种方式读取文件.
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.
例如,要指定一个显式字符集,请使用str.getBytes(Charset.forName("UTF-8"))
. UTF-8是一个很好的选择,因为它始终受支持并且可以编码任何字符.
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.
例如,.properties
文件始终为ISO 8859-1(即Latin-1).对此进行了记录,因此使用哪种编码没有歧义.
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.
这篇关于发现对默认编码的依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!