executing unix programs through java

R

ruds

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?
 
P

PerfectDayToChaseTornados

ruds said:
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 :)
 
R

ruds

LOGGER.error("InterruptedException caught ", ie);
LOGGER.error("exit value was non-zero : \n" +


I didnt understand these two lines
and it gives error Cannot resolve symbol for it.
Do i have to import any class for it?
 
P

PerfectDayToChaseTornados

ruds said:
I didnt understand these two lines
and it gives error Cannot resolve symbol for it.
Do i have to import any class for it?

This was just example code & I was using log4j for logging. You can use
whatever you like for logging. The code I gave you doesn't really do
anything it is an example which you need to understand if you want to use
it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top