--
The class java.lang.ProcessBuilder, in Java 1.5, is used to create operating system processes. Each process builder manages these process attributes : (See Java API Document)
The class java.lang.ProcessBuilder, in Java 1.5, is used to create operating system processes. Each process builder manages these process attributes : (See Java API Document)
- a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. For example, it is common for each conceptual argument to be an element in this list, but there are operating systems where programs are expected to tokenize command line strings themselves - on such a system a Java implementation might require commands to contain exactly two elements.
- an environment, which is a system-dependent mapping from variables to values. The initial value is a copy of the environment of the current process (see System.getenv()).
- a working directory. The default value is the current working directory of the current process, usually the directory named by the system property user.dir.
- a redirectErrorStream property. Initially, this property is false, meaning that the standard output and error output of a subprocess are sent to two separate streams, which can be accessed using the Process.getInputStream() and Process.getErrorStream() methods. If the value is set to true, the standard error is merged with the standard output. This makes it easier to correlate error messages with the corresponding output. In this case, the merged data can be read from the stream returned by Process.getInputStream(), while reading from the stream returned by Process.getErrorStream() will get an immediate end of file.
public class ProcessBuildDemo {
public static void main(String [] args) throws IOException { String[] command = {"CMD", "/C", "dir"}; ProcessBuilder probuilder = new ProcessBuilder( command );
//You can set up your work directory probuilder.directory(new File("c:\\abcddemo")); Process process = probuilder.start(); //Read out dir output InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line; System.out.printf("Output of running %s is:\n", Arrays.toString(command)); while ((line = br.readLine()) != null) { System.out.println(line); } //Wait to get exit value try { int exitValue = process.waitFor(); System.out.println("\n\nExit Value is " + exitValue); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Comments
Post a Comment