java调用shell管道,java调用shell脚本

说到Java调用shell脚本,lz在这里要介绍两个与其相关的类,Runtime和Process。

1.Runtime:该类封装了运行时的环境。每个Java应用程序都有一个Runtime类实例,是应用程序能够与其运行的环境环境相链接。在多线程的操作系统中,可以使用Runtime类来运行其他的线程。

2.Process:该类是一个抽象类,封装了一个进程。Runtime.exec和ProcessBuilder.start都会启动一个进程,并返回该Process子类的一个实例。

下面的例子是如何使用这两个类,在linux系统上用Java调用shell脚本:

public static String executeShell(String shell) {

StringBuilder result = new StringBuilder();

Process process;

try {

process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", shell});

InputStreamReader reader = new InputStreamReader(process.getInputStream());

LineNumberReader input = new LineNumberReader(reader);

String line;

process.waitFor();

while ((line = input.readLine()) != null){

result.append(line);

}

} catch (Exception e) {

e.printStackTrace();

}

return result.toString();

}

waitFor()方法会使主进程一直等待直到子进程的结束。也可以用destory()方法直接杀死子进程。

ProcessBuilder类也可以创建子进程来执行shell:

public static String executeShell(String shell) {

StringBuilder result = new StringBuilder();

Process process;

try {

ProcessBuilder builder = new ProcessBuilder("/bin/sh", "-c", shell);

process = builder.start();

InputStreamReader reader = new InputStreamReader(process.getInputStream());

LineNumberReader input = new LineNumberReader(reader);

String line;

process.waitFor();

while ((line = input.readLine()) != null){

result.append(line);

}

} catch (Exception e) {

e.printStackTrace();

}

return result.toString();

}

还要注意的是,如果shell里面存在管道的话,一定要使用字符串数组new String[]{“/bin/sh”, “-c”, shell}这种形式,才可以获得流。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值