Java库

在Java中,能够经过Runtime类ProcessBuilder类来完结调用外部程序。

Runtime类与ProcessBuilder类

运用Runtime类:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("外部程序途径");

运用ProcessBuilder类:

ProcessBuilder builder = new ProcessBuilder("外部程序途径");
Process process = builder.start();

参数传递

以上两种办法均可发动一个外部进程。假如需求向外部进程传递参数,能够在exec() 或ProcessBuilder结构函数中传递字符数组

String[] cmdarray = {"外部程序途径", "参数1", "参数2"};
Process process = runtime.exec(cmdarray);

履行成果

外部进程的回来成果能够经过process目标获取。能够运用getInputStream() 办法读取外部进程的规范输出流,或者运用getErrorStream() 办法读取错误输出流。

InputStream inputStream = process.getInputStream(); // 规范输出流
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
    System.out.println(line); // 输出每行成果
}

注意:在调用外部程序时一定要当心,因为它可能会引起安全问题和体系溃散等反常情况。主张运用该功能时对外部程序进行充沛的测验和验证

Runtime类的运用

    @Test
    public void runtimeTest() {
        try {
            //获取履行进程
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec("ipconfig");
            //读取输入流
            InputStream inputStream = process.getInputStream();
            //将字节流转成字符流
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk");
            //字符缓冲区
            char[] c = new char[1024];
            int len = -1;
            while ((len = inputStreamReader.read(c)) != -1) {
                String s = new String(c, 0, len);
                System.out.print(s);
            }
            inputStream.close();
            inputStreamReader.close();
            //堵塞当时线程,直到进程退出为止
            process.waitFor();
            int exitValue = process.exitValue();
            if (exitValue == 0) {
                System.out.println("进程正常完毕");
            } else {
                System.out.println("进程反常完毕");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Java实现调用外部程序

ProcessBuilder类的运用

无参数调用

	@Test
    public void processBuilderTest1() {
        ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.command("java");
        //将规范输入流和错误输入流兼并,经过规范输入流读取信息
        processBuilder.redirectErrorStream(true);
        try {
            //发动进程
            Process start = processBuilder.start();
            //获取输入流
            InputStream inputStream = start.getInputStream();
            //转成字符输入流
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "gbk");
            int len = -1;
            //字符缓冲区
            char[] c = new char[1024];
            //读取进程输入流中的内容
            while ((len = inputStreamReader.read(c)) !=-1){
                String s = new String(c, 0, len);
                System.out.print(s);
            }
            inputStreamReader.close();
            inputStream.close();
            //堵塞当时线程,直到进程退出为止
            start.waitFor();
            int exitValue = start.exitValue();
            if (exitValue == 0) {
                System.out.println("进程正常完毕");
            } else {
                System.out.println("进程反常完毕");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Java实现调用外部程序

简单参数调用

processBuilder.command("java","-version");

Java实现调用外部程序

杂乱参数调用

 List<String> command = new ArrayList<>();
        command.add("java");
        command.add("-version");
        processBuilder.command(command);

Apache Commons Exec库

Apache Commons Exec 是一个用于履行外部进程的 Java 库,能够方便地发动和控制进程,而且提供了对输入、输出流的管理和处理

运用过程介绍

1.增加依靠,将Apache Commons Exec库增加到项目中

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-exec</artifactId>
            <version>1.3</version>
        </dependency>

2.结构命令行目标:经过 CommandLine 目标结构需求履行的外部程序和参数。

CommandLine cmdLine = CommandLine.parse("command argument1 argument2");

3.创立履行器目标:经过 DefaultExecutor 目标创立一个履行器,并设置工作目录(可选)。

DefaultExecutor executor = new DefaultExecutor();
executor.setWorkingDirectory(new File("/your/workdir"));

4.创立处理器目标:PumpStreamHandler 目标能够处理输入输出流并存储进程的规范输出和规范错误信息。

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
executor.setStreamHandler(streamHandler);

5.履行命令并等候进程完毕:调用 executor.execute办法履行命令。假如要等候进程履行完结对应的操作,请在此后调用 process.waitFor() 等候进程完毕。履行完结后处理 outputStream 中的输出成果。

executor.execute(cmdLine);
String output = outputStream.toString("UTF-8");
System.out.println(output);

运用实例

    public static void main(String[] args) throws IOException {
        CommandLine cmdLine = CommandLine.parse("java -version");
        DefaultExecutor executor = new DefaultExecutor();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
        executor.setStreamHandler(streamHandler);
        executor.execute(cmdLine);
        String output = outputStream.toString("UTF-8");
        System.out.println(output);
    }

履行输出成果:

java version "1.8.0_271"
Java(TM) SE Runtime Environment (build 1.8.0_271-b09)
Java HotSpot(TM) 64-Bit Server VM (build 25.271-b09, mixed mode)