How to send EOF to a process in Java?

I want to run groff in a java program. The input comes from a string. On the real command line, we finish typing ^D on Linux / Mac. So how to send this terminator to a 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?

+4
source share
2 answers

^D not a character; this is a command interpreted by your shell telling it to close the thread for the process (thus, the process receives EOF on stdin ).

You need to do the same in your code; close and close 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(); ... 
+4
source

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(); } 
0
source

Source: https://habr.com/ru/post/1492573/


All Articles