How to execute a command prompt command & view output in Java

command-promptThe basic part is very easy. To do this, we will use the Runtime’s exec method. The code would be like:

Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("ping localhost");

The command (I’ve used “ping localhost” ) can be anything that your command prompt recognizes. It will vary on UNIX and Windows environment.

Now comes the bit where you would want to see the output of the execution. This I handled by created my wrapper to read the output stream.

I then latch the stream to the process and bingo!

Here’s the wrapper, its getter and the actual code to get the output:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class RuntimeExec {
public StreamWrapper getStreamWrapper(InputStream is, String type){
            return new StreamWrapper(is, type);
}
private class StreamWrapper extends Thread {
    InputStream is = null;
    String type = null;          
    String message = null;

    public String getMessage() {
            return message;
    }

    StreamWrapper(InputStream is, String type) {
        this.is = is;
        this.type = type;
    }

    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuffer buffer = new StringBuffer();
            String line = null;
            while ( (line = br.readLine()) != null) {
                buffer.append(line);//.append("\n");
            }
            message = buffer.toString();
        } catch (IOException ioe) {
            ioe.printStackTrace();  
        }
    }
}
 

// this is where the action is
public static void main(String[] args) {
            Runtime rt = Runtime.getRuntime();
            RuntimeExec rte = new RuntimeExec();
            StreamWrapper error, output;

            try {
                        Process proc = rt.exec("ping localhost");
                        error = rte.getStreamWrapper(proc.getErrorStream(), "ERROR");
                        output = rte.getStreamWrapper(proc.getInputStream(), "OUTPUT");
                        int exitVal = 0;

                        error.start();
                        output.start();
                        error.join(3000);
                        output.join(3000);
                        exitVal = proc.waitFor();
                        System.out.println("Output: "+output.message+"\nError: "+error.message);
            } catch (IOException e) {
                        e.printStackTrace();
            } catch (InterruptedException e) {
                        e.printStackTrace();
            }
            }
}
Get our Articles via Email. Enter your email address.

You may also like...

14 Comments

  1. Mike says:

    see ProcessBuilder

    http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html

  2. Hari says:

    What i liked is the fact that i can convert it to print the output as the native command is being executed, by adding a output statement to the while loop in the StreamWrapper

  3. Ivan says:

    However, if you try some other commands, like “date” or “dir” you will get a file not found IOException. some commands work and other don’t…

  4. Timothy says:

    Doesn’t work with JVM7.

  5. balics says:

    It doesn’t work with me too.. :(

  6. Sameer says:

    Hi Abhinav,

    Your solution was amazing. I was trying to run a python script using a runtime environment within a Servlet. It was getting timed out at proc.waitFor()
    Process proc = rt.exec(“C:/Python27/python ./dev/src/__init__.py”);
    I used jython way of doing it but all are working in a standalone application but not through weblogic. Using this solution I could get the output within the console and I am able to use the output now. I was hunting for it from 4 days..

    Thanks a lot…You rock..

  7. mark says:

    Hello. This is a very wonderful code. However, i had a problem on showing the applications that do not specify its version. The output is not the same as what you see on the control panel.

  8. Otak Jagat says:

    This Is a very help me…

    thk!!!

  9. PT says:

    Why don’t you just save the output in a file by just redirecting the the command line and just get data from the file.If your only concern is to view the output of the execution ?

  10. Pooj says:

    thank a million for the code
    i have to run 3 seperate commands on my terminal to get my output… should i create 3 different process for this in one pgm?
    else how should i modify ur code to accomadate my requirement.
    thank u!!!!!!!!!

  11. Joseph Cotton says:

    Thank you for a well-written code that’s clear and easy to understand. I was able to modify it to run batch scripts on Win7.

  12. guru says:

    is it possible to execute shell script commands in command line using this java program in a ubuntu system

  13. Andy says:

    very helpful. deep and robust though process builder also can improve it a bit.

  14. Parth Mandaliya says:

    Hi,
    Do you know anyway with which we can get continuous o/p from terminal to java or python??
    Like “top” commands fives the continuous output.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.