使用到Process和Runtime两个类,返回值通过Process类的getInputStream()方法获取
package com.xiatian.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Install {
public static void main(String[] args) {
// TODO Auto-generated method stub
Process process = null;
String shpath="/Users/test/install.sh";//.sh文件的绝对路径
String command = "/bin/sh " + shpath;
List<String> processList = new ArrayList<String>();
try {
process = Runtime.getRuntime().exec(command);
BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = input.readLine()) != null) {
processList.add(line);
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String line : processList) {
System.out.println(line);
}
}
}
若报错权限不够,添加 String command1 = “chmod 777 ” + shpath;
亲测可用!
本文介绍了一个使用Java执行Shell脚本的示例,并通过Process和Runtime类获取输出。示例代码展示了如何设置Shell脚本路径,执行命令并读取返回结果。
&spm=1001.2101.3001.5002&articleId=76209612&d=1&t=3&u=b2fcd4dd5a164b9ab19d793b84ebd171)
812

被折叠的 条评论
为什么被折叠?



