首页 > 编程语言 >java 调用系统指令

java 调用系统指令

时间:2022-12-02 10:47:21浏览次数:44  
标签:try 调用 java process pb 指令 线程 reader null

 String msg = "";
        Process process = null;
        try {
            ProcessBuilder pb = new ProcessBuilder();
            //因为process执行命令并不是像窗口中执行shell一样,所以需要添加参数,用于执行脚本
            // pb.command(ffmpegPath, "-y", "-i", filePath, "-ss", n + "", "-f", "image2", targetUrl);
        pb.command("这里写指令");
//processBuilder支持将inputStream与ErrorStream合并为一个Stream,即所有的输出信息都合并到inputStream中,这样做可以减少一个线程
            pb.redirectErrorStream(true);
            process = pb.start();
            //由于process机制原因会导致死锁,所以需要在waitfor方法之前,创建线程用于处理inputstream中缓冲区的数据,这也是为什么要合并inputstream和errorstream的原因,在这里可以少创建一个线程
            readInputStream(process.getInputStream());
            //返回0则表示输出正常
            int resultCode = process.waitFor();
        } catch (Exception e) {
            msg = ExcBox.getExcMsg(e);
            log.info(msg);
        } finally {
            try {
                if (null != process) {
                    process.getErrorStream().close();
                    process.getInputStream().close();
                    process.getOutputStream().close();
                }
            } catch (Exception ignored) {
            }
        }
//创建线程处理输出流【其实就是真实的写指令】
    private static void readInputStream(InputStream in) {
        executor.execute(new Runnable() {
            @Override
            public void run() {
                InputStreamReader reader = null;
                try {
                    reader = new InputStreamReader(in);
                    LineNumberReader line = new LineNumberReader(reader);
                    String str = null;
                    while ((str = line.readLine()) != null) {
                        System.out.println(str);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (reader != null) {
                            reader.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

 

标签:try,调用,java,process,pb,指令,线程,reader,null
From: https://www.cnblogs.com/c2g5201314/p/16943672.html

相关文章