Wednesday, December 11, 2013

Execute system command from Java, using Runtime.getRuntime().exec()

This example demonstrate how to run system commnad ("dir" in Windows) from Java code, and read the output of the command, using Runtime.getRuntime().exec().

package java_process;

import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web java-buddy.blogspot.com
 */
public class Java_Process {

    public static void main(String[] args) {

        // Example to run "dir" in Windows
        String[] command = {"cmd", "/c", "dir"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            Process process = Runtime.getRuntime().exec(command);
            try (InputStream inputStream = process.getInputStream()) {
                int c;
                while ((c = inputStream.read()) != -1) {
                    cmdReturn.append((char) c);
                }
            }
            System.out.println(cmdReturn.toString());

        } catch (IOException ex) {
            Logger.getLogger(Java_Process.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }
}


Runtime.getRuntime().exec()
"dir" in Windows' cmd prompt
Related:
ProcessBuilder to create operating system processes

No comments:

Post a Comment