如果你想创建一个子进程并在它和你的主程序之间交换信息,我认为下面的代码会对你有所帮助。
它通过调用二进制/可执行文件创建一个子进程,然后将某些内容(例如命令)写入其输入流并读取一些文本:
import java.io.*;
public class Call_program
{
public static void main(String args[])
{
Process the_process = null;
BufferedReader in_stream = null;
BufferedWriter out_stream = null;
try {
the_process = Runtime.getRuntime().exec("..."); //replace "..." by the path of the program that you want to call
}
catch (IOException ex) {
System.err.println("error on exec() method");
ex.printStackTrace();
}
// write to the called program's standard input stream
try
{
out_stream = new BufferedWriter(new OutputStreamWriter(the_process.getOutputStream()));
out_stream.write("..."); //replace "..." by the command that the program is waiting for
}
catch(IOException ex)
{
System.err.println("error on out_stream.write()");
ex.printStackTrace();
}
//read from the called program's standard output stream
try {
in_stream = new BufferedReader(new InputStreamReader(the_process.getInputStream()));
System.out.println(in_stream.readLine()); //you can repeat this line until you find an EOF or an exit code.
}
catch (IOException ex) {
System.err.println("error when trying to read a line from in_stream");
ex.printStackTrace();
}
}
}
参考。
http://publib.boulder.ibm.com/infocenter/iseries/v5r4/index.jsp?topic=%2frzaha%2fiostrmex.htm