我有一个C程序可执行文件,我想从java运行,另外我想在运行时为程序提供输入。我写了下面的代码,但它没有显示任何内容。
Java程序:
public static void main(String[] args) throws IOException {
String[] command = {"CMD", "/C", "D:\\TestApp.exe"};
ProcessBuilder probuilder = new ProcessBuilder( command );
Process process = probuilder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running %s is:\n",Arrays.toString(command));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
try {
int exitValue = process.waitFor();
System.out.println("\n\nExit Value is " + exitValue);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
我的C程序如下:
void main()
{
int x,y,res;
printf("\nEnter the First No:");
scanf("%d",&x);
printf("\nEnter the Second No:");
scanf("%d",&y);
res = x + y;
printf ("\nResult is %d",res);
getch();
}
请事先告诉我解决方法,Thanx。 还告诉我在运行时提供输入的代码
答案 0 :(得分:1)
C程序需要输入。要写入流程的标准输入,请写入process.getOutputStream()
,例如:
OutputStream stdin = process.getOutputStream();
stdin.write("3 4\n".getBytes());
stdin.flush();
终止\n
非常重要,因为进程正在等待换行符。
.flush()
调用也很重要,因为Java会缓冲写入,并且此调用会强制写出缓冲区的内容。
将这些行添加到您的代码中,您将获得输出:
Output of running [/path/to/program] is: Enter the First No: Enter the Second No: Result is 7 Exit Value is 0