/**
* 执行脚本
*
* @param shellString 需要执行的脚本内容
* @return
*/
public static int executeShell(String shellString) {
int exitValue = 0;
Process process = null;
try {
String[] cmd = { "/bin/sh", "-c", shellString };
process = Runtime.getRuntime().exec(cmd);
read(process.getInputStream());
read(process.getErrorStream());
exitValue = process.waitFor();
if (0 != exitValue) {
logger.error("execute shell failed. error code is :" + exitValue);
}
} catch (Exception e) {
logger.error("execute shell failed.", e);
} finally {
if (process != null) {
process.destroy();
}
}
return exitValue;
}
/**
* 读取输出流
*
* @param in
* @return
* @throws Exception
*/
public final static String read(InputStream in) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
StringBuffer sb = new StringBuffer();
while (line != null) {
sb.append(line + "\r\n");
line = reader.readLine();
}
reader.close();
in.close();
return sb.toString();
}
Java调用Shell脚本
最新推荐文章于 2024-01-07 12:20:03 发布