要从java运行C程序exectable吗
我有一个C程序可执行文件,我想从java运行,我也想在运行时为程序提供输入。我写了下面的代码,但没有显示任何内容 Java程序:要从java运行C程序exectable吗,java,c,Java,C,我有一个C程序可执行文件,我想从java运行,我也想在运行时为程序提供输入。我写了下面的代码,但没有显示任何内容 Java程序: public static void main(String[] args) throws IOException { String[] command = {"CMD", "/C", "D:\\TestApp.exe"}; ProcessBuilder probuilder = new ProcessBuilder( command );
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();
}
请提前告诉我解决方案。
还要告诉我在运行时提供输入的代码C程序需要输入。要写入进程的标准输入,请写入
process.getOutputStream()
,例如:
OutputStream stdin = process.getOutputStream();
stdin.write("3 4\n".getBytes());
stdin.flush();
终止\n
非常重要,因为进程正在等待换行符。
.flush()
调用也很重要,因为Java会缓冲写入,而此调用会强制写出缓冲区的内容
将这些行添加到代码中后,您将获得以下输出:
为了在运行时验证输入,您可以逐个创建的进程使用outputstream来运行代码进程中的c程序。getOutputStream,写入此outputstream,这将作为c程序的输入。您还可以做一件事,利用JNI直接从java调用c函数,而不是从java运行可执行文件。从process.getErrorStream()读取,然后查看发生了什么。
Output of running [/path/to/program] is:
Enter the First No:
Enter the Second No:
Result is 7
Exit Value is 0