Notes - Java - Do a System Call
Did you ever wonder how to do a System Call (eg. shell or ms-dos[whateverthefucktheycallit]) with Java and get the output (stdout) into a String(s)?
The SHORT version:
import java.lang.*;
import java.io.*;
public class sysCallSimple {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(
Runtime.getRuntime().
exec("/bin/ls -a").
getInputStream()
)
);
while (br.ready()) {
System.out.println(br.readLine());
}
} catch (Exception e) {
System.out.println("Houston we have uhoh: "+e);
}
}
}
The LONG story:
import java.lang.*;
import java.io.*;
public class sysCall {
public static void main(String[] args) {
/* testy
* on multiple lines
* i am*/
try {
// You can execute a process and get a Process
// object back.
Process myProc =
Runtime.getRuntime().exec("/bin/ls -a");
// From the Processs Object you can get an InputStream
// (InputStream is what you want, not OutputStream,
// despite the name)
InputStream is = myProc.getInputStream();
// Send your InputStream to an InputStreamReader:
InputStreamReader isr = new InputStreamReader(is);
// That needs to go to a BufferedReader:
BufferedReader br = new BufferedReader(isr);
// And now, finally, we can get some strings
// back:
while (br.ready()) {
System.out.println(br.readLine());
}
// Other interesting things:
//
// the process must be finished before we can
// determine the exit value:
myProc.waitFor();
int myProcExitVal = myProc.exitValue();
System.out.println("\n\n");
System.out.println("=== Process Finished ===");
System.out.println("Exit Value: " + myProcExitVal);
} catch (IOException e) {
// I haven't figured out how to trip this yet.
// Which makes sense. Java doesn't really know
// if your process failed. That must be determined
// from the exit value.
System.out.println("Houston we have uhoh: "+e);
} catch (InterruptedException e) {
// You need this for that waitFor() diddy.
System.out.println("Something got interrupted, "+
"I guess: "+e);
}
}
}
There _is_ information to be found about Java system calls on the Internets. But most all of it assumes a background in Java. So it may just tell you to get a Process object. It seems like the Javadocs, most Java Programmers, and people who know _only_ Java don't realize that the programming universe does not revolve around Java.