Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send EOF to a process in Java?

Tags:

java

eof

groff

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?

like image 577
Li Dong Avatar asked Jul 21 '13 14:07

Li Dong


People also ask

Is there EOF in Java?

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.

What does EOF return in Java?

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.


2 Answers

^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();
...
like image 58
Brian Roach Avatar answered Oct 10 '22 06:10

Brian Roach


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();
}
like image 30
geekdenz Avatar answered Oct 10 '22 06:10

geekdenz