Java 执行Bash脚本代码

在 Java 中调用 Bash 命令的方法有多种,其中包括但不限于使用 Runtime 类的 exec() 方法、使用 ProcessBuilder 类以及一些第三方库。这些方法允许你在 Java 程序中启动一个外部进程来执行 Bash 命令,并且可以获取到命令执行后的输出、错误信息以及执行的状态等信息。

调用 Bash 命令可能会涉及到一些安全性和可移植性的考虑,因为执行外部命令可能会受到系统环境、权限限制以及操作系统的不同而产生不同的影响。因此,在使用 Bash 命令调用时,务必谨慎处理输入和输出,确保代码的安全性和可靠性。

1. 使用 Runtime 类的 exec 方法

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExecuteBashCommand {
    public static void main(String[] args) {
        try {
            // 构建命令
            String command = "ls -l";

            // 启动进程执行命令
            Process process = Runtime.getRuntime().exec(new String[]{"bash", "-c", command});

            // 读取进程输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待命令执行完毕并获取返回码
            int exitCode = process.waitFor();
            System.out.println("Command executed with exit code: " + exitCode);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2. 使用 ProcessBuilder 类

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ExecuteBashCommand {
    public static void main(String[] args) {
        try {
            // 构建命令
            String command = "ls -l";

            // 启动进程执行命令
            Process process = new ProcessBuilder("bash", "-c", command).start();

            // 读取进程输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待命令执行完毕并获取返回码
            int exitCode = process.waitFor();
            System.out.println("Command executed with exit code: " + exitCode);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值