java调用shell脚本,并得到shell脚本的返回值

2024-12-03 17:13:54
推荐回答(2个)
回答1:

文件名确实不对
.sh文件才是linux下的批处理文件,它不认bat的
另外要保证.sh中调用的其他函数在当前目录下能正常运行

回答2:

用IO截获噻,给你个例子:

public static void main(String[] args) {

String cmd = "pwd";
Runtime run = Runtime.getRuntime();
String result = "";
try {
Process p = run.exec(cmd);
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String lineStr;
while ((lineStr = br.readLine()) != null) {
result += lineStr;
}
br.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(result);
}