java代码调用shell脚本和系统命令

本文介绍了一种在Java代码中执行Linux shell脚本的方法,通过Runtime.getRuntime().exec()函数,详细展示了如何读取脚本的输出和错误信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java代码调用shell脚本和系统命令

如何在java代码中运行shell脚本或者别的linux命令并获取输出结果?

1. 测试脚本

test01.sh
在这里插入图片描述

2. 编写java测试类

package com.company;
import java.io.*;

/**
 * @Author JiangBeiPing
 * @Date 2019/12/19 12:01
 * @Version 1.0
 **/
//测试shell脚本执行
public class test01 {

    public static void main(String[] args) {
        String result = execCmd("bash /jbp/test01.sh", null);
        System.out.println(result);
    }

    //此方法用来执行脚本或命令
    //String cmd:脚本(绝对路径)位置或命令内容
    //File dir:执行命令的子进程的工作目录(null则表示和当前主进程工作目录相同)
    public static String execCmd(String cmd, File dir){
        StringBuilder result = new StringBuilder();
        Process process = null;
        BufferedReader bufrIn = null;
        BufferedReader bufrError = null;
        try {
            //执行命令, 返回一个子进程对象(命令在子进程中执行)
            process = Runtime.getRuntime().exec(cmd, null, dir);
            //方法阻塞,等待命令执行完成
            process.waitFor();
            //获取命令执行结果, 有两个结果: 正常的输出和错误的输出(PS: 子进程的输出就是主进程的输入)
            bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));//正常的输出
            bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));//错误的输出
            //读取输出
            String line = null;
            while ((line = bufrIn.readLine()) != null){
                result.append(line).append('\n');
            }
            while ((line = bufrError.readLine()) != null){
                result.append(line).append('\n');
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeStream(bufrIn);
            closeStream(bufrError);
            //销毁子进程
            if (process != null){
                process.destroy();
            }
        }
        //返回执行结果
        return result.toString();

    }

    //关流方法
    private static void closeStream(Closeable stream){
        if (stream != null){
            try {
                stream.close();
            } catch (Exception e) {

            }
        }
    }

}

3. linux编译并执行该测试类

编译:
在这里插入图片描述
执行:
在这里插入图片描述
成功输出测试脚本内容:Hello World!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值