Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.io.IOException;
- public class CommandExecutor
- {
- /**
- * Run single, external script, program, system command, etc.
- * @author: richarduie [at] yahoo [dot] com
- *
- * Usage syntax is static call to main as:
- * CommandExecutor cmd
- * run command and ignore output of external command process
- * CommandExecutor cmd true
- * run command and capture output of external command process for
- * display in output stream of current process
- *
- * args[0] - command to execute
- * args[1] - optional flag (true/<anything else> to indicate whether
- * to capture command output and display in ouput stream
- * for current process
- *
- * NOTE: if command (args[0]) includes spaces, it must be in quotes, e.g.,
- * [CommandExecutor "ls /" true] lists all subdirectories from root
- * of a *nix installation and writes output to current stream
- */
- public static void main(String[] args) {
- // report usage error and exit, if no arguments
- if (0 == args.length) {
- System.out.println("CommandExecutor.main() - no command given");
- return;
- }
- // if second argument given and value is String "true", capture
- // output from external command output stream and write to output
- // stream for this process
- boolean capture = 1 < args.length && "true".equals( args[1] );
- try {
- // execute command - will run in separate, external
- // process not directly impacting current console
- Process p = Runtime.getRuntime().exec( args[0] );
- // retrieve and display output stream of command process
- if (capture) {
- // for read/write of stdout for command process
- String str;
- // read in process output associated with command
- BufferedReader in = new BufferedReader(
- new InputStreamReader( p.getInputStream( ) )
- );
- // write each line of external command process to
- // current console
- while ( null != (str = in.readLine( ))) {
- System.out.println( str );
- }
- }
- }
- catch (IOException e) {
- System.out.println(
- "CommandExecutor.main() - could not run command:\n" +
- args[0] + "\nException reported was:\n" + e.toString()
- );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement