Executing a system command is relatively simple – once you’ve seen it done the first time. It involves the use of two Java classes, the Runtime class and the Process class. Basically, you use the exec method of the Runtime class to run the command as a separate process. Invoking the exec method returns a Process object for managing the subprocess. Then you use the
getInputStream()and
getErrorStream()methods of the
Processobject to read the normal output of the command, and the error output of the command. What you do with the output of the command executed is entirely up to you and the application you’re creating.
The
ProcessBuilder.start()and
Runtime.execmethods create a native process and return an instance of a subclass of
Processthat can be used to control the process and obtain information about it. The class
Processprovides methods for performing input from the process, performing output to the process, waiting for the process to complete, checking the exit status of the process, and destroying (killing) the process.
The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts.
By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods
getOutputStream(),
getInputStream(), and
getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
Below are two simple Java Examples for your reference.
Example1:
package com.crunchify.tutorials; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author Crunchify.com * */ public class CrunchifyCommandJava { public printOutput getStreamWrapper(InputStream is, String type) { return new printOutput(is, type); } public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); CrunchifyCommandJava rte = new CrunchifyCommandJava(); printOutput errorReported, outputMessage; try { Process proc = rt.exec("ls /Users/<username>/Desktop"); // Process proc = rt.exec("mkdir /Users/<username>/Desktop/test1"); // Process proc = rt.exec("ping http://crunchify.com"); errorReported = rte.getStreamWrapper(proc.getErrorStream(), "ERROR"); outputMessage = rte.getStreamWrapper(proc.getInputStream(), "OUTPUT"); errorReported.start(); outputMessage.start(); } catch (IOException e) { e.printStackTrace(); } } private class printOutput extends Thread { InputStream is = null; printOutput(InputStream is, String type) { this.is = is; } public void run() { String s = null; try { BufferedReader br = new BufferedReader( new InputStreamReader(is)); while ((s = br.readLine()) != null) { System.out.println(s); } } catch (IOException ioe) { ioe.printStackTrace(); } } } }
Output: (As I’ve 7 files and 1 folder on Desktop it returns the same)
Screen Shot 2013-05-10 at 8.42.19 PM.png Screen Shot 2013-05-10 at 8.42.31 PM.png Screen Shot 2013-05-10 at 8.42.40 PM.png Screen Shot 2013-05-10 at 8.43.03 PM.png Screen Shot 2013-05-10 at 8.43.14 PM.png Screen Shot 2013-05-10 at 8.44.28 PM.png Screen Shot 2013-05-10 at 8.44.40 PM.png test1
Example2:
package com.crunchify.tutorials; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Crunchify.com * */ public class CrunchifyRunCommand { public static void main(String[] args) { String s = null; try { Process p = Runtime.getRuntime().exec("ps -few"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command System.out.println("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } System.exit(0); } catch (IOException e) { System.out.println("exception happened - here's what I know: "); e.printStackTrace(); System.exit(-1); } } }
Output:
This will show all running process on your box.
More Java Tutorials.
The post How to Run Windows/Mac Commands in JAVA and Return the Text Result appeared first on Crunchify.