John R
John R

Reputation: 3026

Return Windows cmd text from Java?

I want to return the same text that is returned when I manually type a command into the cmd prompt in Windows. Here is an example that does not work.

import java.io.IOException;

public class Test {

    public static void main(String[] args) throws IOException {
        String g = "";
        Runtime.getRuntime().exec(new String[] {"ipconfig", g});  
        System.out.println(g);
    }
}

I don't know if I should be looking into Runtime.getRuntime()exec because the way I understand the api ( http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Runtime.html ) is that of all of the exec examples, none return a string. The return value (if I understand right) on some is actually a 'process' which I can only guess means nothing gets returned, but the process is started. I used ipconfig in the example, but I actually need to run various diagnostic commands and analyze the string (which I have referred to as the 'cmd prompt').

Upvotes: 0

Views: 2729

Answers (3)

Sibbo
Sibbo

Reputation: 3914

To capture the output of the command, you can use this:

Process p = Runtime.getRuntime().exec(new String[] {"ipconfig", g});
InputStream s = p.getInputStream();

BufferedReader in = new BufferedReader(new InputStreamReader(s));
String temp;

while ((temp = in.readLine()) != null) {
    System.out.println(temp);
}

Please not that the readLine() method will block until it reads an input or the process is terminated.

Upvotes: 2

Barend
Barend

Reputation: 17444

The Java String is immutable, meaning that the "" referenced by g will never change. No code that doesn't do an assignment of g will ever print something other than the empty string to System.out.

Rather than using Runtime.exec, I recommend you use the Commons-Exec library from the Apache Commons project. It provides a much more reliable means of executing external applications (passing the arguments reliably and preventing such things as an unread output stream locking up the program).

You can capture the command output using the PumpStreamHandler and an input stream of your choice.

Upvotes: 2

Daniel Pryden
Daniel Pryden

Reputation: 60957

If you look at the javadoc link you've already posted, you'll see that Runtime.exec() returns a Process object, and the Process class has a method getOutputStream() to get at the standard output stream of the new process.

Upvotes: 1

Related Questions