Re: executing unix programs through java
"ruds" <rudranee@gmail.com> wrote in message
news:1155983221.064144.285110@m73g2000cwd.googlegroups.com...
hello,
I want to know how to execute unix based application programs through
java/JSP/servlet?
is it possible to do system level programming through java like in C?
You can run a shell on the comand line using Runtime.exec()
String[] cmdArray = new String[3];
cmdArray[0] = "/usr/local/bin/bash";
cmdArray[1] = "-c";
cmdArray[2] = "pwd"; // your command
try {
// start command running
Process proc = Runtime.getRuntime().exec(cmdArray);
// get command's output stream and
// put a buffered reader input stream on it
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new
InputStreamReader(istr));
try {
// read output lines from command
String str;
while ((str = br.readLine()) != null) {
// process your results
}
// wait for command to terminate
try {
proc.waitFor();
}
catch (InterruptedException ie) {
LOGGER.error("InterruptedException caught ", ie);
// possibly throw an exception here
}
// check its exit value
if (proc.exitValue() != 0) {
InputStream errorStream = proc.getErrorStream();
BufferedReader brErr = new BufferedReader(new
InputStreamReader(errorStream));
String errStr;
StringBuffer errSB = new StringBuffer();
while ((errStr = brErr.readLine()) != null) {
errSB.append(errStr + "\n");
}
LOGGER.error("exit value was non-zero : \n" +
errSB.toString());
// possibly throw an exception here
}
}
finally {
br.close();
}
}
catch (Exception ex) {
// handle exception
}
Hope this helps :-)
--
pdtct