我已经成功地从Java代码执行了C代码,但我有一个问题,我想将值读入C代码,其中C程序是从Java代码运行的.怎么做?
我的C代码如下.
int main()
{
int op;
printf("\n Hello World... ");
printf("\n Enter any value : ");
scanf("%d",&op);
printf("\n The value entered is : %d",op);
getch();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的java代码如下.
import java.io.*;
public class Test {
public static void main(String args[]) {
try {
String s = " ";
Process processCompile = Runtime.getRuntime().exec("e:/Sample.exe");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(processCompile .getInputStream()));
// read the output from the command
System.out.println("EXE OUTPUT");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
那么,我必须在java代码中进行哪些修改,以便我可以将值输入到C变量中.提前致谢
您需要使用 JNI,而不是 ProcessBuilder。或者您需要将这些值写入文件并从 C 读取该文件。或者您需要将这些值写入进程输入流。让您感到困惑的是,它被称为“outputStream”。
就像是:
OutputStreamWriter osw = new OutputStreamWriter(process.getOutputStream(), "utf-8");
osw.append(String.format("value1=%d value2=%d", value1, value2));
osw.flush();
Run Code Online (Sandbox Code Playgroud)
然后在 C 中从 stdin 读取该字符串。