• Post Reply Bookmark Topic Watch Topic
  • New Topic

Writting a stdout of to a file in Java

 
Kaush Kane
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am running a unix shell script from Java Application. I want to catch the Standard output of that process and write to a particular file. But the file that is getting generated is a zero size file. Could you please help.
Please find the following sample code.

 
Freddy Wong
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Did you close the FileWriter? Prior to closing it, the close() method will do flush().
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
code looks correct to me

file should flush() on close, but if you do not call it the stdout from runProcess.getInputStream(); can hang around for an absurdly long time before being written.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The missing close() is almost certainly the primary problem, but there are a couple others.

One is the empty catch block. This is almost always a bad idea - if an error does occur here, you have no way of knowing what happened. At least put a printStackTrace() in there. Or if you're using some sort of logging framework like log4j, that's even better. Or you could omit the try/catch here entirely, since other methods like readLine() are throwing IOException as well, which means you must have some higher-level try/catch or throws declaration.

The other problem I see is that your code will lose all line separators. The readLine() method reads a line of text and a line separator, but it just returns the line, not including the line separator. And write() doesn't automatically insert a line separator. You could fix this by inserting a line separator yourself after each new line:

Having to use getProperty() is a bit ugly here - you may want to replace it with "\n" or "\r\n", but these will not work exactly the same in Windows and Unix. I prefer a simpler approach - since we had an InputStream to begine with, I'd just use a simple OutputStream to write the data, and forget about Readers and Writers:

Here we don't really care whether what we're copying is a line or not; we just copy whatever has been written, until done. Line separators aren't treated specially as they are for readLine().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!