0

我想从 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);
4

3 回答 3

2

您需要的数据是 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   
    }
于 2013-02-06T20:57:52.907 回答
0

您可以执行以下操作:

        Process proc = Runtime.getRuntime().exec("net start");          
        InputStreamReader isr = new InputStreamReader(proc.getInputStream());
        BufferedReader br = new BufferedReader(isr);

        String temp = null;
        while (( temp = br.readLine() ) != null)
               System.out.println(temp);
于 2013-02-06T21:06:16.637 回答
0

看看 ProcessBuilder。

使用低于 Java 1.5 Runtime.getRuntime().exec(...)

于 2013-02-06T20:36:55.283 回答