gpt4 book ai didi

Java运行Windows命令行命令返回一个值

转载 作者:行者123 更新时间:2023-12-01 14:52:08 24 4
gpt4 key购买 nike

我想从java运行Windows命令行命令并将结果返回到java中。这可能吗?

例如,我想做以下事情

Object returnValue = runOnCommandLine("wmic cpu get LoadPercentage");//在本例中,returnValue 是字符串形式的 cpu 负载百分比

编辑:我能够让这个工作

InputStream inputStream = new ProcessBuilder("wmic", "cpu", "get", "status").start().getInputStream();
StringWriter writer = new StringWriter();
IOUtils.copy(inputStream, writer);
String theString = writer.toString();
System.out.println("My string: " + theString);

最佳答案

您需要的数据是commandOutput。

    String cmd = "wmic cpu get LoadPercentage";
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader stdin = new BufferedReader(
new InputStreamReader(p.getInputStream()));
StringBuilder commandOutput = new StringBuilder();
String line;
while ((line = stdin.readLine()) != null) {
commandOutput.append(line);
}
int exitValue = -1;
try {
exitValue = p.waitFor();
} catch (InterruptedException e) {
// do something here
}

关于Java运行Windows命令行命令返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14738276/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com