Java本地连接linux,执行命令并输出结果

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;
    }
posted @ 2020-08-12 14:15  鱼蛋炒饭  阅读(670)  评论(0)    收藏  举报