Thursday, December 13, 2012

Execute linux bash command and read its output from java Program


This is a very frequent snippet that you want and spend a lot of time researching on the basic technique. Following is the java code snippet.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class cmdExecute2 {
public static void main(String[] args) {
String osName = System.getProperty("os.name");
String rawVersion = null;
StringBuffer outputReport = new StringBuffer();
String cmdToExecute = "awk '/Service.*DisplayGroupName.*Name.*ProductID/' /usr/local/services.conf";
if (osName != null && osName.indexOf("Windows") == -1
&& osName.indexOf("SunOS") == -1) {
Runtime rt = Runtime.getRuntime();
BufferedReader is = null;
try {
// execute the RPM process
Process proc = rt.exec(new String[]{"sh","-c",cmdToExecute});
// read output of the rpm process
is = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String tempStr = "";
while ((tempStr = is.readLine()) != null ) {
outputReport.append(tempStr.replaceAll(">", "/>\n"));
tempStr = "";
}
int inBuffer ;
while ((inBuffer = is.read()) != -1) {
outputReport.append((char) inBuffer);
}
// rawVersion = is.readLine();
// response.append(rawVersion);
is.close();
proc.destroy();
} catch (IOException ioe) {
System.out.println("Exception executing command " + cmdToExecute + "\n" + ioe);
} finally {
try {
is.close();
} catch (final IOException ioe) {
System.out.println("Cannot close BufferedStream" + ioe);
}
}
}
System.out.println(outputReport.toString());
} // end of main
} // end of class

Followers