InputStreamReader字节流的中文编码处理

背景:最近写一个小功能,Java Project 的编码是UTF-8,打印出来的windows cmd 命令输出所有中文都是乱码。
----execCmd: cmd /c ant
'ant' �����ڲ����ⲿ���Ҳ���ǿ����еij���
���������ļ���

分析和查找了一堆资料后,找到问题出在InputStreamReader和BufferedReader两个方法使用上。
1)BufferedReader:从字符流中读取文本
从字符输入流中读取文本,缓冲各个字符,从而实现字符、数组和行的高效读取。 可以指定缓冲区的大小,或者可使用默认的大小。大多数情况下,默认值足够大

2)InputStreamReader:将字节流转换为字符流。有多个重载方法,

其中一个是:
public InputStreamReader(InputStream in):该解码过程将使用file.encoding默认的字符编码,如果没有设置,则使用ISO 8859_1

/**
* Constructs a new {@code InputStreamReader} on the {@link InputStream}
* {@code in}. ****This constructor sets the character converter to the encoding
* specified in the "file.encoding" property**** and falls back to ISO 8859_1
* (ISO-Latin-1) if the property doesn't exist.
*
* @param in
* the input stream from which to read characters.
*/

问题来了:cmd 输出默认是GBK编码的,而我的Java Project是UTF-8,如果直接调用InputStreamReader(InputStream in)则相当于使用UTF-8对原本GBK的字节进行处理,那必然是乱码啊。使用另外一个重载方法就ok了:InputStreamReader(InputStream in,final String charsetName)

原代码:

Process p = Runtime.getRuntime().exec(cmd);
// 正确输出流
InputStream input = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
saveToFile(line, "runlog.log", false);
}

修正后的代码:

Process p = Runtime.getRuntime().exec(cmd);
// 正确输出流
InputStream input = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input,"GBK"));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
saveToFile(line, "runlog.log", false);
}

InputStreamReader字节流的中文编码处理