当前位置:首页 > 编程笔记 > 正文
已解决

Java执行cmd或者shell命令,并获取结果

来自网友在路上 187887提问 提问时间:2023-11-08 19:59:45阅读次数: 87

最佳答案 问答题库878位专家为你答疑解惑

已经做了处理,兼容windows和linux系统和编码,不会乱码。 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;public class CommandExecutorUtils {public static String executeCommand(String command) {Charset charset = System.getProperty("os.name").toLowerCase().contains("win") ? Charset.forName("GBK") : Charset.defaultCharset();String os = System.getProperty("os.name").toLowerCase();List<String> commands = new ArrayList<>();// 判断操作系统类型,并准备命令if (os.contains("win")) {// Windowscommands.add("cmd");commands.add("/c");} else {// Unix/Linux/MacOScommands.add("/bin/sh");commands.add("-c");}commands.add(command);// 执行命令并获取结果try {ProcessBuilder processBuilder = new ProcessBuilder(commands);Process process = processBuilder.start();// 获取输出String output = readStream(process.getInputStream(), charset);// 等待进程结束int exitCode = process.waitFor();if (exitCode == 0) {return output;} else {String error = readStream(process.getErrorStream(), charset);throw new IOException("Command execution failed with exit code " + exitCode + " and error: " + error);}} catch (IOException | InterruptedException e) {Thread.currentThread().interrupt();return "Error: " + e.getMessage();}}private static String readStream(InputStream inputStream, Charset charset) throws IOException {BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, charset));StringBuilder builder = new StringBuilder();String line;while ((line = reader.readLine()) != null) {builder.append(line);builder.append(System.getProperty("line.separator"));}return builder.toString();}public static void main(String[] args) {// 示例命令String command = "ping www.a.shifen.com";// 在Windows上使用GBK编码读取输出,在Linux上使用系统默认编码String result = CommandExecutorUtils.executeCommand(command);System.out.println(result);}
}

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Java执行cmd或者shell命令,并获取结果":http://eshow365.cn/6-35545-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!