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

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("
");
            }
            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("获取的结果是"+"
"+result);

    }
}

3.Linux 上执行jar包显示结果

你可能感兴趣的:(java,java,后端)