如何将字符串数据从 Java 发送到 Windows 下的 C++ 控制台应用程序?我正在尝试这样做:
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
String o = ...;
proc.getOutputStream().write(o.getBytes());
但是当我这样做时,我从来没有在 C++ 端看到它:
ReadFile(stdin_h,buf, sizeof(buf), &bytes, 0)
ReadFile
永远不会返回。
接下来是进一步的阐述和示例代码。
我编写了一个简单的 C++ 控制台 (Win32) 应用程序,它从 STDIN 读取数据并根据输入执行操作。
现在我想编写一个 Java 应用程序来“驱动”C++ 应用程序。 Java 应用程序应该:
- 使用
Runtime.exec()
启动 C++ 应用程序 - 将字符串数据写入 C++ 应用的 STDIN
- 重复直到死亡。
我的 Java 应用程序似乎可以正常工作,但 C++ 应用程序从未收到任何关于 STDIN 的数据。
这是 C++ 应用程序:
int main()
{
ofstream f("c:\\temp\\hacks.txt");
HANDLE stdin_h = GetStdHandle(STD_INPUT_HANDLE);
DWORD file_type = GetFileType(stdin_h);
if( file_type != FILE_TYPE_CHAR )
return 42;
f << "Pipe" << endl;
for( bool cont = true; cont; )
{
char buf[64*1024] = {};
DWORD bytes = 0;
if( ReadFile(stdin_h,buf, sizeof(buf), &bytes, 0) )
{
string in(buf,bytes);
cout << "Got " << in.length() << " bytes: '" << in << "'" << endl;
f << "Got " << in.length() << " bytes: '" << in << "'" << endl;
if( in.find('Q') )
cont = false;
}
else
{
cout << "Err " << GetLastError() << " while reading file" << endl;
f << "Err " << GetLastError() << " while reading file" << endl;
}
}
}
这是 Java 方面:
public static void main(String[] args) {
Runtime rt =Runtime.getRuntime();
try {
Process proc = rt.exec("c:\\dev\\hacks\\x64\\debug\\hacks.exe");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
int a = 0;
while(a < 5)
{
String o = (a == 4 ? "Q\n" : "A\n");
proc.getOutputStream().write(o.getBytes());
System.out.println("Wrote '" + o + "'");
++a;
}
try {
proc.waitFor();
// TODO code application logic here
} catch (InterruptedException ex) {
Logger.getLogger(Java_hacks.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(Java_hacks.class.getName()).log(Level.SEVERE, null, ex);
}
}
Java 端似乎工作正常,但我从未收到过 C++ 端的字符串。
我是不是做错了什么?如何将字符串数据从 Java 发送到 Windows 下的 C++ 控制台应用程序?
最佳答案
为什么在写入 5 个字符串后 不刷新 Java 端的输出流?
proc.getOutputStream().flush();
关于java - 写入在 Windows 下的 Java 应用程序中生成的 C++ 控制台应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11302745/