在Windows下编写Java应用程序中生成的C++控制台应用程序

Joh*_*ing 5 c++ java windows console

如何将Java中的字符串数据发送到Windows下的C++控制台应用程序?我想这样做:

BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(proc.getOutputStream()));
String o = ...;
proc.getOutputStream().write(o.getBytes());
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,我从未在C++方面看到它:

ReadFile(stdin_h,buf, sizeof(buf), &bytes, 0)
Run Code Online (Sandbox Code Playgroud)

ReadFile 永远不会回来

以下是进一步的详细说明和示例代码.


我编写了一个简单的C++控制台(Win32)应用程序,它从STDIN读取并根据输入执行操作.

现在我想编写一个Java应用程序来"驱动"C++应用程序.Java应用程序应该:

  1. 使用启动C++应用程序 Runtime.exec()
  2. 将字符串数据写入C++应用程序的STDIN
  3. 重复,直到死亡的时候.

我的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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Java端似乎工作正常,但我没有收到C++方面的字符串.

我在这里做错了吗?如何将Java中的字符串数据发送到Windows下的C++控制台应用程序?

t0m*_*13b 4

为什么在写入 5 个字符串后不在 Java 端刷新输出流?

proc.getOutputStream().flush();
Run Code Online (Sandbox Code Playgroud)

  • +1:呃,因为我不够聪明,不知道我应该这么做。:) 等一下,让我试试。 (2认同)