Matt Winstanley
Matt Winstanley

Reputation: 48

Why does BufferedReader fail if BufferedWriter is still open?

I am trying to run a .exe file from a java application and would like to be able to use it (for now) like a terminal where i can write to the .exe then read back from it before writing it again.

My issue is that the code only works when the writer is closed before the reader attempts to read from the inputstream.

String line = "", prev = "";
    Scanner scan = new Scanner(System.in);

    ProcessBuilder b = new ProcessBuilder("myexe");
    b.redirectErrorStream(true);

    Process p = b.start();
    OutputStream stdin = p.getOutputStream();
    InputStream stdout = p.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));


    System.out.println ("->");
    while (scan.hasNext()) {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
        String input = scan.nextLine();
        if (input.trim().equals("exit")) {
            writer.write("C");
        } else {
            writer.write(input);
        }
        writer.flush();

        //writer.close();
        while ((line = reader.readLine ()) != null) {
            System.out.println ("[Stdout] " + line);

            if (line.equals(prev)){
                break;
            }
            prev = line;
          }
          reader.close();
        }

So my question is, am i doing something wrong with the ProcessBuilder? I have read about not reading the output correctly can cause the system to hang. But this doesnt explain why it hangs when the writer is still open?

Upvotes: 0

Views: 181

Answers (1)

Matt Winstanley
Matt Winstanley

Reputation: 48

The issue was actually with my C compiled .exe. When it was running, the application was printing an output, therefore working in cmd terminal however i had not flushed the buffer after each command sent. Once i had done this, the java application would recognise each command as they were sent.

Upvotes: 1

Related Questions