Java 调用Linux 命令,并获取命令执行结果

版权声明:Boomlee https://blog.csdn.net/BoomLee/article/details/82985125

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包显示结果

猜你喜欢

转载自blog.csdn.net/BoomLee/article/details/82985125