Java Streams  «Prev 

Java Streams - Shell Commands

  End-of-stream> Kill application> Suspend app and return to shell>
Unix Ctrl-D Ctrl-C Ctrl-Z
Windows
(DOS prompt)
Ctrl-Z [Enter] Ctrl-C No such command

Running External System Commands

This takes away from the portability of Java applications.
For instance, if you write a Java application on a Unix system, you might be interested in running the "ps -ef" command, and reading the output of the command. For Unix systems this is great however, since this same program will not work on a Windows system because the ps command is not available on Windows. Putting portability aside for this article, we will demonstrate a method that can be used to run system commands.
You can invoke a Unix shell like you would invoke any other program. Use the -c option to pass the command to run as a parameter.
Also make sure to use the exec(String[]) method, and not exec(String), to avoid the command being tokenized the wrong way:
String[] cmd = {"/bin/sh", "-c", "/bin/cat alias > bias"};
Process p = Runtime.getRuntime().exec(cmd);

To read and write from/to the process, get the input, output, and error streams from the Process instance you just created:
InputStream in = p.getInputStream();
InputStream err = p.getErrorStream();
OutputStream out = p.getOutputStream();

Then read from/write to these streams as usual.
Note that streams are named relative to the Java application. Anything written to the OutputStream is piped to the standard input of the process you created. Anything written by the process to stdout/stderr is piped to the InputStreams obtained from p.getInputStream() and p.getErrorStream() respectively.