Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic returning 0 on piped input  RSS feed

Carey Brown
Saloon Keeper
Posts: 2840
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My simple (I thought) goal was to write a small java program that
I can run from a Windows command line. I would like it to accept
a list of files, either as command line arguments, or from the
output of another executable program piped into

new_program <list-of-files>


old_program | new_program

The new_program first checks to see if > 0
so that the program doesn't block if there's no input on

Then I wrap in a BufferedReader so that I can call the
readLine() method.

And, I'm not sure what difference this makes, I launch new_program
from a .BAT file (new_program.bat).

If the "old_program" is an .EXE file then everything seems to go
according to plan. If the "old_program" is itself a Java program
launched by a .BAT file then the call to available() returns 0.

I put a kludge in the new_program to sleep for a second prior to
calling available() and that appears to work. However I don't
think that that is a "proper" solution and may still fail depending
on the timing of the old_program.

Is there a better way of handling this?

Thanks in advance,

Mike Simmons
Ranch Hand
Posts: 3090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In general, available() isn't very reliable. If it returns 0, that may just mean that there are no bytes available right now. But if you read() and block until something is available, that may change. I know it may seem like there should be bytes available right away in your scenario, but depending on how your OS and scripts set up the pipeline, the Java process may be up and ready for input before bytes are available as input. Furthermore different InputStream implementations handle availalbe() differently - remember it's an "approximation" according to the API. Personally I can't remember finding available() to be useful for anything.

From what you've said, I think it would make more sense to first check if there are any command-line arguments. If there are, use them, and don't bother trying to read If there aren't any arguments, then read Forget about checking available(), just call one of the read() methods. You can do this in separate thread if you want to be able to have your program not block in this scenario, but that will increase complexity a bit. I think it's simplest to require that either the user will provide command line arguments, or you will block waiting for stdin.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!