[英]Communicating with C++ process from Java
首先,我在網站上看到有關此問題的一些問題,但沒有找到解決我問題的答案。
我有一個用Java編寫的程序,它調用了一個用C ++編寫的cmd程序。 (這是一個假設,因為我沒有實際的來源)我知道C ++程序的預期I / O,在cmd中它是兩行輸出,然后等待字符串輸入。 我知道程序的第一行輸出是通過錯誤流,並且我正確地接收了它(這是預期的),但是我沒有得到錯誤或輸入流的第二行。 我嘗試在第一行(錯誤行)之后立即寫入程序,但沒有卡住,但是沒有響應。 我嘗試為每個流使用3個不同的線程,但是同樣,在第一行之后輸入/錯誤流中什么也沒收到,並且程序對通過輸出流進行寫入沒有響應。
我的初始化程序是:
Process p = Runtime.getRuntime().exec("c:\\my_prog.exe");
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
有沒有可能,或者取決於C ++程序?
謝謝,Binyamin
如果要從Java調用C和C ++之類的本機應用程序,則需要使用JNI。
我建議在程序啟動時將其輸入程序中,並在需要時將其適當地用作輸入。
這是我在Java中執行任何命令行的方式。 該命令行可以執行任何程序:
private String executionCommandLine(final String cmd) {
StringBuilder returnContent = new StringBuilder();
Process pr;
try {
Runtime rt = Runtime.getRuntime();
pr = rt.exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = null;
while ((line = input.readLine()) != null) {
returnContent.append(line);
}
input.close();
LOG.debug(returnContent.toString());
// return the exit code
pr.waitFor();
} catch (IOException e) {
LOG.error(e.getMessage());
returnContent = new StringBuilder();
} catch (InterruptedException e) {
LOG.error(e.getMessage());
returnContent = new StringBuilder();
}
return returnContent.toString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.