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

查看:106
本文介绍了我们的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.0\bin\\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天全站免登陆