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:
<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>
In this example, we:
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!