java 实现 调用Linux命令工具类

2022-08-14 11:03:25 浏览数 (1)

目录

  • 1 代码实现

1 代码实现

代码语言:javascript复制
public class CommandUtil {

    public static String execuCmd(String cmd) {
        System.out.println("执行命令[ "   cmd   "]");
        Runtime run = Runtime.getRuntime();
        try {
            Process process = run.exec(cmd);
            String line;
            BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            StringBuffer out = new StringBuffer();
            while ((line = stdoutReader.readLine()) != null ) {
                out.append(line);
            }
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            process.destroy();
            return out.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

0 人点赞