java中FileOutputStream中文亂碼問題解決辦法

這篇文章主要介紹了java中FileOutputStream中文亂碼問題解決辦法的相關資料,需要的朋友可以參考下

java中FileOutputStream中文亂碼問題解決辦法文章源自四五設計網(wǎng)-http://www.wasochina.com/39086.html

使用FileOutputStream序列化可以直接向文件寫入文本內(nèi)容,代碼如下:文章源自四五設計網(wǎng)-http://www.wasochina.com/39086.html

1
2
3
FileOutputStream outStream = new FileOutputStream(file);
outStream.write(str.getBytes());
outStream.close();

但這里的字符串如果包含中文,就會出現(xiàn)亂碼,這是因為FileOutputStream是字節(jié)流,將文本按字節(jié)寫入文件,而一個漢字是兩個字節(jié),無法一次寫入,就會出現(xiàn)亂碼,解決方法是使用OutputStreamWriter將字節(jié)流轉換為字符流寫入,同時指定utf-8編碼。文章源自四五設計網(wǎng)-http://www.wasochina.com/39086.html

代碼如下:文章源自四五設計網(wǎng)-http://www.wasochina.com/39086.html

1
2
3
OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
oStreamWriter.append(str);
oStreamWriter.close();

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!文章源自四五設計網(wǎng)-http://www.wasochina.com/39086.html 文章源自四五設計網(wǎng)-http://www.wasochina.com/39086.html

我的微信
微信掃一掃
weinxin
我的微信
惠生活福利社
微信掃一掃
weinxin
我的公眾號
 

發(fā)表評論

匿名網(wǎng)友
:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

拖動滑塊以完成驗證