Java执行cmd命令.并打印输出. 解决中文乱码 .

package org.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class Main {
    public static void main(String[] args) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "echo 您好!我是Java.");
            processBuilder.redirectErrorStream(true); // 将错误流合并到输出流中
            Process process = processBuilder.start();

            // 读取进程的输出流,指定编码为GBK
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            int exitCode = process.waitFor();
            System.out.println("命令执行完成,退出码:" + exitCode);
        } catch (IOException | InterruptedException e) {
            System.out.println("Error U !");
        }
    }
}

  如上图,执行的代码是  "echo 您好!我是Java."

 

posted @ 2023-12-09 15:07  挪威森林猫Zzz  阅读(198)  评论(0编辑  收藏  举报