Java运行cmd命令获取的结果打印出来乱码怎么解决?

ㅤㅤㅤㅤ
  • 3
新手上路,请多包涵

我用exec方法执行控制台命令,然后用BufferedReader读取结果,打印出来的是乱码。


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Test {
    public static void main(String[] args) {
        Process process = null;
        String[] cmd = {"cmd", "/C", "help"};
        try {
            process = Runtime.getRuntime().exec(cmd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert process != null;
        InputStreamReader reader = new InputStreamReader(process.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(reader);
        String message;
        while (true) {
            try {
                if ((message = bufferedReader.readLine()) == null) {
                    break;
                }
                  // 无用操作
//                System.out.println(new String(message.getBytes("UTF-8"), "UTF-8"));
                System.out.println(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

打印结果:

�й�ij���������ϸ��Ϣ������� HELP ������
ASSOC          ��ʾ���޸��ļ���չ��������
ATTRIB         ��ʾ������ļ����ԡ�
BREAK          ���û������չʽ CTRL+C ��顣
BCDEDIT        �����������ݿ��е������Կ����������ء�
CACLS          ��ʾ���޸��ļ��ķ��ʿ����б�(ACL)��
回复
阅读 378
1 个回答
InputStreamReader reader = new InputStreamReader(process.getInputStream(), Charset.forName("gbk"));

改这行就行了

宣传栏