调用系统命令
执行系统命令相对来说比较容易,可以通过使用 Runtime
和 Process
两个类来执行。我们可以通过Process的getInputStream和getErrorStream两个方法获取到结果和错误信息的输入流,下面就是实例代码,改代码通过执行 ps -ef
命令来获取结果(执行在mac或者linux上)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
package map;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
* Created by benjamin on 12/23/15. */ public class JavaRunCommand {
public static void main(String[] args) { String s = null; try { Process p = Runtime.getRuntime().exec("ps -ef"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("标准输出命令\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); }
System.out.println("标准错误的输出命令(如果存在):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } System.exit(0); } catch (IOException e) { System.out.println("异常发生: "); e.printStackTrace(); System.exit(1); } } }
|
调用管道命令
上一节的调用的只是简单的mac命令,那么如果我想调用管道命令,例如:
ps -ef | grep java
那么该如何调用呢?实际上只需要构建ProcessBuilder,传入一个命令的list集合即可。它的返回值也是Process对象。下面的用法和Runtime类似。
下面的代码进行了实例说明:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
|
package map;
import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner;
* Created by benjamin on 12/24/15. */ public class JavaRunCommandWithPipeline {
public static void main(String[] args) throws IOException { String s = null; List<String> commands = new ArrayList<String>(); commands.add("/bin/sh"); commands.add("-c"); commands.add("ps -ef | grep chrome");
ProcessBuilder builder = new ProcessBuilder(commands);
Process start = builder.start(); Scanner scanner = new Scanner(start.getInputStream()); Scanner errorScanner = new Scanner(start.getErrorStream());
System.out.println("命令执行结果为: \n"); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } System.out.println("命令执行错误结果为: \n"); while (errorScanner.hasNextLine()) { System.out.println(scanner.nextLine()); }
if (scanner != null) { scanner.close(); } if (errorScanner != null) { errorScanner.close(); } System.exit(0); } }
|