来自我们 Java 程序的外部程序 [英] External program from our Java program

查看:26
本文介绍了来自我们 Java 程序的外部程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用 Java 编写一个程序来执行另一个程序?此外,该程序的输入应从我们的程序中给出,该程序的输出应写入文件.

How can I write a program in Java that will execute another program? Also, the input of that program should be given from our program and the output of that program should be written into a file.

这是我获取输出的一小部分代码:

This is my small set of code to get its output:

Process p = Runtime.getRuntime().exec("C:\j2sdk1.4.0in\helloworld.java");
BufferedReader input =
        new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) 
  System.out.println(line);

input.close();

这是我的一组代码,但这会引发 IOException.

This was my set of code but this throws an IOException.

推荐答案

Java 为此提供的 API 是 ProcessBuilder.设置工作目录和传递参数相对简单.

The API that Java offers for this is the ProcessBuilder. It is relatively straightforward to set working directory and pass parameters.

有点棘手的是传递 STDIN 并读取 STDERR 和 STDOUT,至少对于其中的非平凡大小,因为您需要启动单独的线程以确保相应的缓冲区被清除.否则,您调用的应用程序可能会阻塞,直到它可以写入更多输出,如果您还等待该进程完成(不确保 STDOUT 被读取),您将死锁.

What is a little tricky is passing STDIN and reading STDERR and STDOUT, at least for non-trivial sizes thereof, because you need to start seperate threads to make sure the respective buffers get cleared. Otherwise the application that you called might block until it can write more output, and if you also wait for that process to finish (without making sure that STDOUT gets read), you will deadlock.

这篇关于来自我们 Java 程序的外部程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆