0

I would like to run a windows command line command from java and return the result into java. Is this possible?

for example, I would like to do the following

Object returnValue = runOnCommandLine("wmic cpu get LoadPercentage"); //In this case, returnValue is the cpu load percent as a String

Edit: I was able to get this working

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);
Sukhmeet Singh
  • 29
  • 1
  • 11
sworded
  • 2,419
  • 4
  • 31
  • 48
  • It take a look at [this](http://stackoverflow.com/questions/11604657/spawning-multiple-process-using-process-builder-from-java/11604831#11604831) and [this](http://stackoverflow.com/questions/12892665/how-to-capture-the-exit-status-of-a-shell-command-in-java/12892737#12892737) and [this](http://stackoverflow.com/questions/13227893/how-to-execute-cmd-commands-via-java-swing/13228238#13228238) – MadProgrammer Feb 06 '13 at 20:44
  • Or check out http://javaevangelist.blogspot.nl/2011/12/java-tip-of-day-using-processbuilder-to.html – Sebastiaan van den Broek Feb 06 '13 at 20:47

3 Answers3

2

Data you need is 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   
    }
0

Take a look into ProcessBuilder.

Below Java 1.5 Runtime.getRuntime().exec(...) was used.

qkrijger
  • 26,686
  • 6
  • 36
  • 37
thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
  • 2
    Much easier to use [ProcessBuilder](http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html) - solves many of the common mistakes people make with `Runtime#exec` - IMHO – MadProgrammer Feb 06 '13 at 20:38
  • @MadProgrammer It appears Oracle says the same thing in the docs. `ProcessBuilder` is preferred in 1.5 and above. Thanks for the info. – thatidiotguy Feb 06 '13 at 20:40
0

You could do the following:

        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);
buxter
  • 583
  • 4
  • 14