如何编写一个程序,该程序将运行另一个java程序(应该调用该程序)从该程序向该程序提供输入并获取输出并将输出打印到文件。
答案 0 :(得分:8)
示例:
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Process p = pb.start();
InputStream in = p.getInputStream();
OutputStream out = p.getOutputStream();
// Write to input of the program using outputstream here
...
// Read output of program from input stream here
// ...
FileOutputStream fileOut = new FileOutputStream("output.txt");
BufferedInputStream bIn = new BufferedInputStream(in);
byte buf = new byte[4096];
int count;
while ((count = bIn.read(buf)) != -1) {
fileOut.write(buf, 0, count);
}
...
fileOut.close();
bIn.close();
// Exception handling is left as an exercise for the reader :-P