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 !"); } } }
如上图, 红色部分内容为执行的cmd代码. 也可替换成你自己想要的代码.
标签:java,打印输出,process,cmd,乱码,io,import,Java From: https://www.cnblogs.com/alpha-cat/p/17890996.html