Java 呼叫Linux 命令,並獲取命令執行結果
阿新 • • 發佈:2018-11-11
1.工具類
public class ExcuteLinux { public static String exeCmd(String commandStr) { String result = null; try { String[] cmd = new String[]{"/bin/sh", "-c",commandStr}; Process ps = Runtime.getRuntime().exec(cmd); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); StringBuffer sb = new StringBuffer(); String line; while ((line = br.readLine()) != null) { //執行結果加上回車 sb.append(line).append("\n"); } result = sb.toString(); } catch (Exception e) { e.printStackTrace(); } return result; } }
2.呼叫
public class main {
public static void main(String[] args) {
String result = ExcuteLinux.exeCmd("ifconfig");
System.out.println("獲取的結果是"+"\n"+result);
}
}
3.Linux 上執行jar包顯示結果