您的位置:首页 > 运维架构 > Shell

java执行shell命令或者脚本,返回结果到程序

2014-02-24 14:44 831 查看
// 读取shell脚本或者命令
public static void runShell(String shellString) {
try {
Process process = Runtime.getRuntime().exec(shellString);
int exitValue = process.waitFor();
if (0 != exitValue) {
log.error("call shell failed. error code is :" + exitValue);
} else {
getShellResult(process);
}
} catch (Throwable e) {
System.out.println(e);
log.error("call shell failed. " + e);
}
}
//收集shell脚本运行的结果集
public static List<String> getShellResult(Process process) {
List<String> processList = new ArrayList<String>();
try {
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);
}

return processList;
}

public static void main(String[] args) {
runShell("/lw/shell/shell.txt");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  shell 脚本 java