Question

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?

Was it helpful?

Solution

^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();
...

OTHER TIPS

I wrote this utility method:

public static String pipe(String str, String command2) throws IOException, InterruptedException {
    Process p2 = Runtime.getRuntime().exec(command2);
    OutputStream out = p2.getOutputStream();
    out.write(str.getBytes());
    out.close();
    p2.waitFor();
    BufferedReader reader
            = new BufferedReader(new InputStreamReader(p2.getInputStream()));
    StringBuilder sb = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
    }
    return sb.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top