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);
2

3 Answers 3

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   
    }
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

0

Take a look into ProcessBuilder.

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

2 Comments

Much easier to use ProcessBuilder - solves many of the common mistakes people make with Runtime#exec - IMHO
@MadProgrammer It appears Oracle says the same thing in the docs. ProcessBuilder is preferred in 1.5 and above. Thanks for the info.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.