Java调用Linux下的shell命令并将结果以流的形式返回
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main
{
public static void main(String[] args)
{
//得到Java进程的相关Runtime运行对象
Runtime runtime = Runtime.getRuntime();
try
{
//利用exec()方法执行shell 命令 ls -al /root ,并且返回一个Process对象 也就是子进程
//ps:这里都以最简单的shell命令举例。
Process process = runtime.exec("ls -al /root");
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String temp = null;
while ((temp = bufferReader.readLine()) != null)
{
stringBuffer.append(temp);
stringBuffer.append("\n");
}
System.out.println(stringBuffer);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
public class ShellExcuter {
private static Logger logger = Logger.getLogger(ShellExcuter.class);
/**
* 跑linux命令
* @param cmd
* @param args
*/
public static void runShell(String cmd, String[] args) {
InputStream in;
BufferedReader br;
OutputStream out;
BufferedWriter bw;
try {
for (String arg : args) {
cmd = cmd +" "+arg;
}
// String[] cmds = new String[] {
// "/bin/sh",
// "-c",
// cmd };
logger.info(cmd);
Process process = Runtime.getRuntime().exec(cmd);
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String temp = null;
while ((temp = bufferReader.readLine()) != null) {
logger.info(temp);
}
BufferedReader bufferReader2 = new BufferedReader(new InputStreamReader(process.getErrorStream()));
while ((temp = bufferReader.readLine()) != null) {
logger.info(temp);
}
bufferReader.close();
bufferReader2.close();
process.waitFor();
process.destroy();
} catch (Throwable e) {
logger.error("执行linux命令出错:" + e.getMessage());
e.printStackTrace();
}
}
}