findbugs異常(2):Reliance on default encoding

1. 官方說明:

Reliance on default encoding
Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly.

2. 出錯代碼片段:

   

response.setHeader("Content-Disposition", "attachment;filename="
                    + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));

3. 說明:
String.getBytes()依賴於系統編碼,雖然方便,但是一旦使用就變成了一個技術債務,因爲系統的默認編碼是不可預知的

如果要避免這個錯誤,需要將編碼指定好,即:

String.getBytes("GBK")

這是getBytes的一個重載方法,可以指定getBytes使用的編碼

PS:常用編碼中,筆者暫時只發現GBK編碼中漢字佔2個字節,其餘均佔3個字節

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章