我正在尝试从 Java 调用 C 程序并捕获标准输出。这是我的代码:
try {
ProcessBuilder pb = new ProcessBuilder("helloworld.exe");
pb.redirectErrorStream(true); // Merge std out and std err into same stream
program = pb.start(); // Start program
BufferedReader input = new BufferedReader(new InputStreamReader(program.getInputStream()));
line = input.readLine();
while (line != null) {
System.out.println(line);
line = input.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
这是一个示例 C 程序:
int main(){
printf("Hello world\n");
}
当我正在执行的程序(在本例中为 helloworld)中没有 getchar()
时,这可以正常工作。但是,如果我在 printf 之后立即添加 getchar()
,我将永远无法从输入流中获取任何信息。有什么想法吗?
谢谢
最佳答案
正如 Kyle 所说,您可能需要在调用 print 后刷新输出流,以确保字符确实无延迟地转到标准输出。您应该在两个程序中都这样做。这可以在 C 语言中使用 fflush(stdout);
完成,也可以在 Java 中使用 System.out.flush()
之类的东西完成。
--大卫
关于java - 使用 getchar() 从 C 程序获取 Java 标准输出时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6550224/