13.07.2015 Views

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

Java™ Application Development on Linux - Dator

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

112Chapter 4Where Am I? Executi<strong>on</strong> C<strong>on</strong>text<strong>on</strong> the opposite side of the I/O fence. The external program’s output becomesour input.)Example 4.4 shows a Java program that can invoke an arbitrary <strong>Linux</strong>program. The output of the program is displayed.Example 4.4 Java program to execute any <strong>Linux</strong> programimport java.io.*;public classExec{public static voidmain(String [] args)throws IOExcepti<strong>on</strong>{String ln;Process p = Runtime.getRuntime().exec(args);BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));while((ln = br.readLine()) != null) {System.out.println(ln);}System.out.println("returns:" + p.exitValue());} // main} // class ExecThe command-line arguments are taken to be the command to be executedand its arguments. For example:$ java Exec ls -lBe aware that in this example, <strong>on</strong>ly the standard output is captured anddisplayed from the invoked process. Error messages written to standard errwill be lost, unless you modify the program to handle this. We leave that as anexercise for the reader.Check your <strong>Linux</strong> knowledge—see if you understand the distincti<strong>on</strong>. Ifyou invoke the sample Exec program as:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!