sh 启动java_在java中启动sh脚本

1.先在对应目录下创建一个sh的脚本文件:

可以进入linux,输入 nano test.sh  会在当前目录下生成一个test.sh文件

可以在该文件中写入shell脚本的内容,如:

#!/bin/sh

echo 'Hello World!'

然后ctrl+x  选择Y 保存文件。

2.chmod 777 test.sh给该文件赋予操作权利

3../test.sh  运行脚本,会打出'Hello World!' ,说明sh脚本文件创建成功。

4.在java中运行test.sh文件:

synchronized (lock){

Process process = null;

BufferedReader input = null;

try {

final String shScriptPath = //绝对路径

LOG.info("shScriptPath--------->"+shScriptPath);

String[] cmd = {"/bin/sh", "-c", shScriptPath};

process = Runtime.getRuntime().exec(cmd);

input = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;

StringBuffer sb = new StringBuffer("");

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

sb.append(line).append("\r\n");

}

LOG.info("Shell命令执数据---" + sb);

if(process != null){

int extValue = process.waitFor(); //返回码 0 表示正常退出 1表示异常退出

if(0 == extValue){

LOG.info("Shell命令执行完毕");

return true;

}

}

return false;

} catch (Exception e) {

LOG.error("Shell命令执行异常",e.getMessage());

return false;

} finally {

try {

input.close();

process.destroy();

} catch (Exception e) {

LOG.error("流或process销毁异常",e.getMessage());

}

}

}这样就ok了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值