File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes I/O and Streams and the fly likes nio and getRuntime()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "nio and getRuntime()?" Watch "nio and getRuntime()?" New topic

nio and getRuntime()?

Mr.David Shapiro
Ranch Hand

Joined: Apr 18, 2005
Posts: 53
Does anybody have an example of using nio channels or bytebuffers to read stdout/stderr of a command run with getRuntime?
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Well, Runtime (or rather, Process) doesn't have any special hook for NIO, so you'd have to use the InputStreams and put wrappers around them:

What you do with them after that is up to you - they work like other NIO classes, if you have examples of those. As usual for a Process, you should probably read the two channels in separate threads. Or you could use a ProcessBuilder instead, and set it up to send both standard out and error out to the same stream:

"I'm not back." - Bill Harding, Twister
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46437
I had a similar problem using Runtime.exec() to compile a .c file with gcc. This is what I tried:-You have to make sure to empty both Streams quickly, otherwise there is a risk of deadlock. I took all the output from the two Streams from the process, and used separate Threads to put the output into List<String> objects. Because this takes longer than the myProcess.waitFor() call, I introduced a 1-second delay with Thread.sleep(). After that, one can simply print the contents of the two Lists. You will find a reference to an article from about 6� years ago in one of the documentation comments.

See whether that lot helps.
I agree. Here's the link:
subject: nio and getRuntime()?
It's not a secret anymore!