java 写入txt文件的中文乱码是怎么回事?

Python016

java 写入txt文件的中文乱码是怎么回事?,第1张

原因是写入时使用的字符编码和期望的不一致导致的。

java工作区统一编码。统一为utf-8

这个就是输出流的编码问题吧?如果你在输出时指定好具体的编码,或者说指定跟原网页一直的编码。

如果你期望写到文件中的汉字是 GBK编码,可以写文件时,将字符串准换成 GBK编码的byte[]。

网页编码和输出流编码一致。

HttpServletRequest request = ServletActionContext.getRequest()

if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") >0){

try {

filename = new String(filename.getBytes("UTF-8"), "ISO8859-1")

} catch (Exception e) {

e.printStackTrace()

}//firefox浏览器}

}else {

try {

filename = URLEncoder.encode(filename, "UTF-8")

} catch (Exception e) {

e.printStackTrace()

}//IE浏览器

}