• 欢迎访问少将全栈,学会感恩,乐于付出,珍惜缘份,成就彼此、推荐使用最新版火狐浏览器和Chrome浏览器访问本网站。
  • 吐槽,投稿,删稿,交个朋友,商务沟通v:ai_draw
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏少将全栈吧

解决FindBugs报错:Found reliance on default encoding in XXX

点滴 admin 7年前 (2017-09-05) 7766次浏览 已收录 0个评论 扫描二维码

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

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.

String.getBytes()依赖于系统编码,虽然方便,但是一旦使用就变成了一个技术债务,因为系统的默认编码是不可预知的

如果要避免这个错误,需要将编码指定好,即:

String.getBytes(“GBK”)

这是getBytes的一个重载方法,可以指定getBytes使用的编码

PS:常用编码中,笔者暂时只发现GBK编码中汉字占2个字节,其余均占3个字节

参考:

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

喜欢 (0)
[🍬谢谢你请我吃糖果🍬🍬~]
分享 (0)
关于作者:
少将,关注Web全栈开发、项目管理,持续不断的学习、努力成为一个更棒的开发,做最好的自己,让世界因你不同。
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址