Wednesday, December 11, 2013

ProcessBuilder to create operating system processes

This example have the same result of last post "Runtime.getRuntime().exec()", but using ProcessBuilder.

ProcessBuilder to create operating system processes


package java_processbuilder;

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_ProcessBuilder {

    public static void main(String[] args) {

        // Example to run "dir" in Windows
        String[] command = {"cmd", "/c", "dir"};
        StringBuilder cmdReturn = new StringBuilder();
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            Process process = processBuilder.start();
            
            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_ProcessBuilder.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
        
    }
    
}


No comments:

Post a Comment