Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Knute Snortum
  • paul wheaton
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Ron McLeod
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Tim Holloway
  • Carey Brown
  • salvin francis

nio and getRuntime()?

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does anybody have an example of using nio channels or bytebuffers to read stdout/stderr of a command run with getRuntime?
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Marshal
Posts: 65448
248
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
If you open the box, you will find Heisenberg strangling Shrodenger's cat. And waving this tiny ad:
professionally read, modify and write PDF files from Java
https://products.aspose.com/pdf/java
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!