Sunday, November 02, 2008

Launch OS Applications From Java

It's not a good idea to reinvent the wheel when programming for various platforms; you'll live happier when you can just use what the operating system already offers - straight from your Java application. This is especially helpful if the OS program you are interested in supports command-line invocations: this tip shows how to run those programs and capture the output those programs would produce back into your Java application. Then you could use regular expression or other means to parse the output.
Here's all you need:
    public static List<String> runCommand (String... cmd) {
List<String> output = new ArrayList<String>();
try {
// Create the process
ProcessBuilder pb = new ProcessBuilder(cmd);
Process proc = pb.start();

// Obtain the input stream
InputStream is = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);

// Read what is returned by the command
String line;
while ((line = br.readLine()) != null) {
output.add(line);
}

// Close the stream
br.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}

// Return the output
return output;
}
As a utility method, just pass it an array of strings used to build the command, first the fully-qualified name of the program to invoke, followed by program arguments. For example, if I needed to run a Perl script called lockdown.pl and have the Perl interpreter at C:\Perl\perl.exe, then the string array would be something like {"c:\\perl\\perl.exe", "c:\\security\\lockdown.pl"} - notice the use of fully-qualified names everywhere - this process is cross-platform and doesn't look up environment variables to help resolve relative filenames.
The methods returns the output - what you would have seen on the console - as a list line by line. Easy stuff.