// Java program to perform a Unix command on Suns // By Dan Hyde, October 4, 2002 // See Java classes "Process" and "Runtime" in API // // To use, enter the Unix command on the command line as: // // java UnixCommand ls -l // // The command can use redirection of input and out with < and > // // java UnixCommand date > out import java.io.*; // need for IOException class UnixCommand { UnixCommand(String [] args){ try{ // commands need to be in a String array // with one token per element String [] command = new String[3]; command[0] = "xterm"; command[1] = "-bg"; command[2] = "white"; // To use "command" variable uncomment the .exec( command ) // line and comment the .exec( args ) line // Process p = Runtime.getRuntime().exec( command ); Process p = Runtime.getRuntime().exec( args ); // wait until it's done executing if needed p.waitFor(); // read the output from the command // NOTE: Some commands also send parts of their output to a // "standard error stream", when an error occurs. // Then you need to use getErrorStream() as well. InputStream p_out = p.getInputStream(); BufferedReader out_buf = new BufferedReader( new InputStreamReader(p_out)); String line = ""; while( (line = out_buf.readLine() ) != null) { System.out.println("SOUT: " + line ); } // Note: getOutputStream() is used to connect to the standard // input of the command's process if you need to supply input. } catch( InterruptedException e2){ System.out.println(" error in waitFor "); } catch( IOException e ){ System.out.println(" Bad I/O "); } } public static void main(String args[]){ UnixCommand a = new UnixCommand( args ); } }