简体   繁体   中英

Java I/O to pipe

For some reason this code only works when I close the output stream. How can I get it to work without having to close it?

I want to keep it open so I could keep sending data to the process without restarting it.

ProcessBuilder pbuilder = new ProcessBuilder(procCmds);
            pbuilder.directory(new File(workingDir));
            Process p = pbuilder.start();

    BufferedWriter outputStream = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    String str = "hello world heard from java\n";
    outputStream.write(str, 0, str.length());
    outputStream.flush();
    System.out.println("wrote " + str);
    BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while((line=errorStream.readLine())!=null)
        System.out.println(line);
    while((line=inputStream.readLine())!=null)
        System.out.println(line);

    //p.waitFor();
    outputStream.close();
    errorStream.close();
    inputStream.close();

You need to either merge the error and inputs streams or else read one of them in a separate thread. At present you are attempting to read the error stream to EOS, which only happens when the process exits, so you never get to read the input stream at all. You won't get EOS on the input stream either until the process exits, so reading it to EOS doesn't really make sense either if you have further output to provide. Probably you should read both streams in separate threads.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM