Run an external program at the same time and communicate with it through stdin / stdout

I want to be able to run an external program at the same time as my Java code, that is, I want to run the program, and then return control to the calling method while maintaining the external program. Then the Java code will continue to generate input and send it to an external program and receive output.

I do not want to download an external program, since it has very high overheads. What is the best way to do this? Thanks!

+6
source share
4 answers

Take a look at ProcessBuilder . After you set up ProcessBuilder and ProcessBuilder start , you will have a Process handle with which you can feed and read.

Here is a snippet you can start:

 ProcessBuilder pb = new ProcessBuilder("/bin/bash"); Process proc = pb.start(); // Start reading from the program final Scanner in = new Scanner(proc.getInputStream()); new Thread() { public void run() { while (in.hasNextLine()) System.out.println(in.nextLine()); } }.start(); // Write a few commands to the program. PrintWriter out = new PrintWriter(proc.getOutputStream()); out.println("touch hello1"); out.flush(); out.println("touch hello2"); out.flush(); out.println("ls -la hel*"); out.flush(); out.close(); 

Conclusion:

 -rw-r--r-- 1 aioobe aioobe 0 2011-04-08 08:29 hello1 -rw-r--r-- 1 aioobe aioobe 0 2011-04-08 08:29 hello2 
+11
source

You can run an external application using Runtime.getRuntime (). exec (...)

To send data to an external program, you can either send data to the Processes output stream (you return a Process object from exec), or you can open sockets and exchange data this way.

+2
source

I think you will find Javadoc for the java.lang.Process class useful. It should be noted that you can receive input and output streams from the process for communication with it during operation.

0
source

Secondly, the answer to the question about using ProcessBuilder . If you want to know more about this and why you should prefer it to Runtime.exec() , see this entry in the Java glossary . It also shows how to use threads to communicate with an external process.

0
source

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


All Articles