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?
End Of File In Java In Java when a file is read the value generally stored in a variable like a String. If the end of the file is reached the returned value will be a null which is simply nothing. We can check the end of the file if the returned value is null like below.
The eof() function is used to check if the End Of File (EOF) is reached. It returns 1 if EOF is reached or if the FileHandle is not open and undef in all other cases.
^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();
...
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With