ProcessBuilder创建本地进程执行命令

ProcessBuilder类是J2SE 1.5在java.lang中新添加的一个新类,可以用来创建子进程,并且比用Runtime.exec使用更方便。


在CommandExecutor类中,SCRIPT_DIR表明脚本所在的目录位置,示例程序默认为系统的用户目录。

public static final String SCRIPT_DIR = System.getProperty("user.dir");

可以自定为自己的所需目录:

public static final String SCRIPT_DIR = “你的目录”;

 

其中的invoke方法可以调用脚本,结果返回调用脚本所产生的信息,注意此时的信息包含执行正确的信息或者执行错误的信息,不能根据此方法确定命令或者脚本一定执行成功,此方法适用于不需要返回值的执行命令。

 

其中的execute方法,第一个参数为你预期的执行结果,如示例代码调用查看Java命令返回信息是否包含1.6.0_26,所以调用例子为:

CommandExecutor executor = CommandExecutor.createCommandExecutor();

System.out.println(executor.execute("1.6.0_26", "java", "-version"));

 

如果是在linux平台想调用脚本命令可以改为:

executor.execute("预期参数", "sh", "test.sh")


下面代码是使用ProcessBuilder创建进行执行命令的代码示例:

 1 /**
2 * The tool provides the method to invoke the system command or the script.
3 * @author gabriel
4 * @date 2012-3-15
5 */
6 public final class CommandExecutor {
7
8 public static final String SCRIPT_DIR = System.getProperty("user.dir");
9
10 private CommandExecutor() {}
11
12 /**
13 * create a command executor instance.
14 * @return
15 */
16 public static CommandExecutor createCommandExecutor() {
17 return new CommandExecutor();
18 }
19
20 /**
21 * invoke the command.
22 * @param command
23 * @return
24 */
25 public synchronized String invoke(String ...command) {
26 ProcessBuilder pb = new ProcessBuilder(command);
27 //set the default directory of the script file.
28 pb.directory(new File(SCRIPT_DIR));
29
30 pb.redirectErrorStream(true);
31
32 Process proc = null;
33 BufferedReader br = null;
34 InputStream is = null;
35 StringBuffer msg = new StringBuffer();
36 try {
37 proc = pb.start();
38 is = proc.getInputStream();
39 br = new BufferedReader(new InputStreamReader(is));
40 String tmp = "";
41 while(null != (tmp = br.readLine())) {
42 msg.append(tmp);
43 msg.append(System.getProperty("line.separator"));
44 }
45 } catch (IOException e) {
46 }
47 return msg.toString();
48 }
49
50 /**
51 * verify the result of the invoking command.
52 * @param pattern
53 * @param command
54 * @return
55 */
56 public boolean execute(String pattern, String ...command) {
57 String target = invoke(command);
58 return null != target && target.contains(pattern);
59 }
60
61
62 public static void main(String[] args) throws IOException {
63 CommandExecutor executor = CommandExecutor.createCommandExecutor();
64 System.out.println(executor.execute("1.6.0_26", "java", "-version"));
65 }
66 }

转载于:https://www.cnblogs.com/smalldirector/archive/2012/03/15/2398296.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值