I am looking for java examples or library that will help me integrate this into a Struts2/Spring application. Many build systems such as Luntbuild or Hudson have this functionality, I thought I would ask if any one knows of a standalone example before I attempted to dig it out of one of those. I glanced at Quartz job scheduling framework also, but I haven't found the UI hooks yet. Do I just need to read from a file with a JSP include?
Asked
Active
Viewed 3,570 times
1 Answers
2
If I understand what you are trying to do, this is one way in Java. This executes the ls command and then captures the shell output and writes it back to System.out.
public class TestShell {
public static void main(String[] args)
{
try
{
String cmd = "ls\n";
Process p = Runtime.getRuntime().exec(cmd);
p.waitFor();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
while(r.ready()) {
System.out.println(r.readLine());
}
}
catch (Throwable t)
{
t.printStackTrace();
}
}
}

DMKing
- 1,705
- 1
- 10
- 13
-
you could also add: BufferedReader r2 = new BufferedReader(new InputStreamReader(p.getErrorStream())); while(r2.ready()) { System.out.println(r2.readLine()); } To get standard error output too – MatthieuP Jan 09 '09 at 18:26
-
How important is the p.waitFor()? – Epitaph Jan 09 '09 at 19:30
-
1Supposedly it waits for the process to exit. I'm not sure if you can read before that time or not. I ultimately did not need the shell output for what I was doing so I didn't explore it fully. I do know that running under windows trying to do the same thing I had timing issues – DMKing Jan 10 '09 at 06:08
-
(cont.'d) with the shell closing and I would not get a full directory listing. – DMKing Jan 10 '09 at 06:09