java UTF-8转GBK不乱码

1、通过读写文件的方式进行编码转换,示例代码如下所示:

public static void main(String args[]) throws IOException{
String utf8 = "utf8.txt";
FileInputStream fr = new FileInputStream(utf8);
InputStreamReader isr = new InputStreamReader(fr,"UTF-8");
BufferedReader in = new BufferedReader(isr);
String s = in.readLine();
if(s==null){
System.out.println(utf8);
return;
}else{
System.out.println(s);
}
FileOutputStream fos = new FileOutputStream("GBK.txt");
OutputStreamWriter out = new OutputStreamWriter(fos,"GBK");
out.write(s.substring(1));
out.close();
}

2、通过new String的方式进行编码转换

new String("需要转换的字符串".getBytes("GBK"),"UTF-8")

将UTF-8转换为GBK但是根据字符串数量的不同会存在乱码

且确保使用时对应的代码是GBK编码才行。

备注:通过cpdetector开源框架进行编码检测,通过文件读写的方式来进行是比较方便的。