
Executing System Commands in Java
This article discusses executing system commands in Java using the Runtime.exec() method. The method allows you to launch a separate process and interact with its standard input, output, and error streams.
To demonstrate its usage, consider the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <code class = "java" > public class ImprovedCommandExecution {
public static void main(String[] args) {
try {
Runtime r = Runtime.getRuntime();
Process p = r. exec ( "uname -a" );
p.waitFor();
BufferedReader b = new BufferedReader( new InputStreamReader(p.getInputStream()));
StringBuilder output = new StringBuilder();
String line;
while ((line = b.readLine()) != null) {
output.append(line).append( "\n" );
}
b.close();
System.out.println(output);
} catch (Exception e) {
e.printStackTrace();
}
}
}</code>
|
Copy after login
In this example, we:
- Get a reference to the Runtime object, which allows us to execute system commands.
- Use exec() to start a process that executes the "uname -a" command.
- Wait for the process to finish using waitFor().
- Obtain the process's input stream and use a BufferedReader to read its output.
- Append each line of output to a StringBuilder and print the final output.
This code stores the output from the system command in a String, making it easy to use within your Java program.
The above is the detailed content of How Can I Execute System Commands in Java?. For more information, please follow other related articles on the PHP Chinese website!