温馨提示×

java如何调用shell脚本传参数

小亿
148
2023-09-15 11:04:35
栏目: 编程语言

在Java中调用Shell脚本并传递参数有多种方法,以下是其中一种常见的方法:

  1. 使用java.lang.Runtime类的exec()方法来执行Shell命令。

  2. exec()方法中传递Shell脚本命令和参数。

下面是一个示例代码,演示如何在Java中调用Shell脚本并传递参数:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ShellScriptExample {
public static void main(String[] args) {
try {
// 定义Shell脚本命令和参数
String[] cmd = { "sh", "/path/to/your/script.sh", "param1", "param2" };
// 执行Shell脚本
Process process = Runtime.getRuntime().exec(cmd);
// 读取Shell脚本输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待Shell脚本执行完成
int exitCode = process.waitFor();
System.out.println("Shell脚本执行完成,退出码:" + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}

在上面的示例代码中,将/path/to/your/script.sh替换为实际的Shell脚本路径,并在数组cmd中传递所需的参数。然后,使用Runtime.exec()方法执行Shell脚本。通过BufferedReader读取Shell脚本的输出,并等待Shell脚本执行完成。

请注意,上述示例仅适用于Linux或Mac系统,如果在Windows系统上运行,需要更改Shell脚本命令和参数的格式。

0