How to send EOF to a process in Java?

Li Dong picture Li Dong · Jul 21, 2013 · Viewed 8.3k times · Source

I want to run groff in a Java program. The input comes from a string. In real command line, we will terminate the input by ^D in Linux/Mac. So how to send this terminator in Java program?

String usage +=
    ".Dd \\[year]\n"+
    ".Dt test 1\n"+
    ".Os\n"+
    ".Sh test\n"+
    "^D\n";    // <--- EOF here?
Process groff = Runtime.getRuntime().exec("groff -mandoc -T ascii -");
groff.getOutputStream().write(usage.getBytes());
byte[] buffer = new byte[1024];
groff.getInputStream().read(buffer);
String s = new String(buffer);
System.out.println(s);

Or any other idea?

Answer

Brian Roach picture Brian Roach · Jul 21, 2013

^D isn't a character; it's a command interpreted by your shell telling it to close the stream to the process (thus the process receives EOF on stdin).

You need to do the same in your code; flush and close the OutputStream:

String usage =
  ".Dd \\[year]\n" +
  ".Dt test 1\n" +
  ".Os\n" +
  ".Sh test\n";
...
OutputStream out = groff.getOutputStream();
out.write(usage.getBytes());
out.close();
...