Java本地执行linux命令的方法,程序如下:
public String executeLinuxCmd(String cmd) {
System.out.println("开始执行命令: " + cmd);
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(cmd);
InputStream in = process.getInputStream();
StringBuffer out = new StringBuffer();
byte[] b = new byte[8192];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
System.out.println("命令执行结果:" + out.toString());
in.close();
process.destroy();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}