java之中文乱码处理

有些时候,比如文件操作的时候,特别是文件中有中文,会规定用GBK格式,这时读写文件,可能会出现中文乱码

  • 资源文件乱码
  • 文件内容乱码

 

资源文件乱码:

  解决:

PropertiesUtil proper = new PropertiesUti()
String str = new String(proper.getValue("destFileName")
.getBytes("iso-8859-1"), "GBK");//取出资源文件中的内容,然后进行编码转换

或者
URLEncoder.encode(filename,"utf-8");

文件内容乱码:

  操作中文内容的文件时,不能用流读写,否则不能无法对编码格式进行转换

  解决:

// 输入流
BufferedReader in = in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "GBK"));

// 读出文件全部内容(内容和文件中的格式一致,含换行)
            while ((line = in.readLine()) != null) {
                String strtemp = line.replace(oldStr, newStr);
                sb.append(strtemp + "\n");
            }
// 输出流
BufferedWriter out= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "GBK"));

//写入文件
out.write(sb.toString());

 

 

  

 

posted @ 2019-08-13 13:18  bitbetter  阅读(198)  评论(0编辑  收藏  举报