在Java中调用Shell脚本并传递参数有多种方法,以下是其中一种常见的方法:
-
使用
java.lang.Runtime
类的exec()
方法来执行Shell命令。 -
在
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脚本命令和参数的格式。