搜索
首页Javajava教程Java怎么实现调用外部程序

Java怎么实现调用外部程序

May 20, 2023 pm 11:04 PM
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");

    可以重写为: 创建执行器对象需要使用 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);

    调用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)

    以上是Java怎么实现调用外部程序的详细内容。更多信息请关注PHP中文网其他相关文章!

    声明
    本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
    JVM性能与其他语言JVM性能与其他语言May 14, 2025 am 12:16 AM

    JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

    Java平台独立性:使用示例Java平台独立性:使用示例May 14, 2025 am 12:14 AM

    JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

    JVM架构:深入研究Java虚拟机JVM架构:深入研究Java虚拟机May 14, 2025 am 12:12 AM

    TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

    JVM:JVM与操作系统有关吗?JVM:JVM与操作系统有关吗?May 14, 2025 am 12:11 AM

    JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

    Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性Java:写一次,在任何地方跑步(WORA) - 深入了解平台独立性May 14, 2025 am 12:05 AM

    Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

    Java平台独立性:与不同的操作系统的兼容性Java平台独立性:与不同的操作系统的兼容性May 13, 2025 am 12:11 AM

    JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

    什么功能使Java仍然强大什么功能使Java仍然强大May 13, 2025 am 12:05 AM

    JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

    顶级Java功能:开发人员的综合指南顶级Java功能:开发人员的综合指南May 13, 2025 am 12:04 AM

    Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。

    See all articles

    热AI工具

    Undresser.AI Undress

    Undresser.AI Undress

    人工智能驱动的应用程序,用于创建逼真的裸体照片

    AI Clothes Remover

    AI Clothes Remover

    用于从照片中去除衣服的在线人工智能工具。

    Undress AI Tool

    Undress AI Tool

    免费脱衣服图片

    Clothoff.io

    Clothoff.io

    AI脱衣机

    Video Face Swap

    Video Face Swap

    使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

    热门文章

    热工具

    SecLists

    SecLists

    SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

    SublimeText3 英文版

    SublimeText3 英文版

    推荐:为Win版本,支持代码提示!

    SublimeText3 Linux新版

    SublimeText3 Linux新版

    SublimeText3 Linux最新版

    VSCode Windows 64位 下载

    VSCode Windows 64位 下载

    微软推出的免费、功能强大的一款IDE编辑器

    SublimeText3 Mac版

    SublimeText3 Mac版

    神级代码编辑软件(SublimeText3)