Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

About Runtime

Status
Not open for further replies.

WhiteSox

Programmer
May 22, 2001
20
0
0
US
old question, new variation.

we all know the following piece does work well:

String cmd = "ls";
Process proc = Runtime.getRuntime().exec(cmd);

here, the external command is simple enough.

now, i wanna play with pipe. for example, i wanna execute
"ls -l | grep -i abc" with Runtime (i think it's the only way). i've studied the article at but their samples don't work for me, neither in windows nor in linux.

any hints are highly appreciated.
 
Hi WhiteSox,

I was also unable to get those examples work, but I checket at one similar example and it seemed to work.

So try this:

_____________________________________________

String[] cmd = { "sh", "-c", "ls -al | grep java" };
try
{

Process p = Runtime.getRuntime().exec(cmd);

BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

String str = null;
while((str = br.readLine()) != null)
{
System.out.println(str);
}
}
catch(IOException ioe)
{
System.out.println(ioe.toString());
}

Well, this works at Linux, for some reason you have to call a new shell... I don't have much experience of Runtime, but I hope this helped you.
 
Vepo,

Your code does really work for me, though it doesn't look good. i know it's J's fault, not yours. Thanks a lot for your hint.

I've figured out what's preventing me from running the samples @ at add "proc.waitFor()" before retrieving error message as the following:

FileOutputStream fos = new FileOutputStream(args[0]);
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("ls -l");

proc.waitFor();

// any error message?
StreamGobbler errorGobbler = new
StreamGobbler(proc.getErrorStream
(), "ERROR");

Thanks again,

WS
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top