Java System Calls
1. The class [Link] class features a static method called getRuntime( ) which retrieves the current Java Runtime Environment. That is the only way to obtain a reference to the Runtime object. With that reference, you can run external commands by invoking the Runtime classs exec( ) method.
Runtime rt = [Link](); Process p = [Link]( external command);
2. Overloaded exec( ) methods
public public public public Process Process Process Process exec(String command) exec(String[ ] cmdArray) exec(String command, String[ ] envp) exec(String[] cmdArray, String[ ] envp)
3. The exec( ) method creates an operating system specific process (a running program) with a reference to a Process class returned to the Java VM. The Process class is an abstract class, because a specific subclass of Process exists for each operating system. 4. exitValue( ) method of the Process class returns the exit value for the subprocess. It will thrown an IllegalThreadStateException if the external process has not yet completed. You can use the waitFor( ) method that causes the current thread to wait until the process represented by this Process object has terminated.
int exitVal = [Link]( ); int exitVal = [Link]();
5. To handle output text from an external program, we make use of IO streams, assuming that the external command is an executable program.
InputStream stderr = [Link](); InputStreamReader isr = new InputStreamReader(stderr); BufferedReader br = new BufferedReader(isr); InputStream stdin = [Link](); InputStreamReader reader = new InputStreamReader(stdin); BufferedReader b = new BufferedReader(reader);
6. For an non-executable program (especially in Windows), execute either [Link] or [Link] depending on the Windows operating system you use.
String cmd[] = new String[3]; cmd[0] = [Link]; cmd[1] = /C; cmd[2] = dir *.java; p = [Link](cmd);
[Link] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 import [Link].*; import [Link].*; public class MyExecutioner { public static void main(String[] args){ try { Runtime rt = [Link](); String[] cmd = new String[3]; cmd[0] = "cmd"; cmd[2] = args[0]; cmd[1] = "/C"; Process p = [Link](cmd); //Error detection here BufferedReader br = new BufferedReader(new InputStreamReader([Link]())); String line = ""; while( (line = [Link]()) != null ){ [Link]("ERROR: " + line); } //get output from the subprocess BufferedReader in = new BufferedReader(new InputStreamReader([Link]())); while((line = [Link]()) != null){ [Link]("OUTPUT: " + line); } int exitVal = [Link](); [Link]("Is there an error? " + exitVal); } catch(Throwable t){ [Link](); } }
10/30/2012
} /* getErrorStream() - returns the input stream connected to the error output of the subprocess getInputStream() - returns the input stream connected to the normal of the subprocess getOutputStream() - returns the output stream connected to the normal input of the subprocess */