I have an InputStream that is set up to handle local files, but want to add the ability to read from a file over a network at a later time. I assume InputStream is geared for this already.
The problem I am having is, apparently InputStream is not guaranteed to have data available at any given time, and data may become available later. Not sure I’m understanding that correctly. There’s no method to determine an absolute size of available data (as number of bytes) or even if the InputStream is closed. It seems like if there’s a file there, it must have something available. A method that is handling the InputStream is probably going to read from it, and if no data is available, there isn’t any reason to keep it around. What’s worse is I can’t even tell if there is any data available.
So my question is, for a file being read over a network or locally, how can I determine if it is open/closed, and possibly determine the size of the file on the other end? Why is this class so bare?
The
InputStreamabstract class is for reading bytes from any source, not just a file. Its descendants provide methods for specific sources. For example,FileInputStreamcan be used to read bytes from a file, whileSocketInputStreamis used to read bytes from a socket.This is why
InputStreamdoesn’t offer any methods for determining the file size, because it would make no sense for sources other than files.I’m not sure what exactly you mean by reading file over a network. If it means reading a file from a remote filesystem (e.g. over NFS), then you can use the
length()method in theFileclass to get the size of the file:You can determine whether the
FileInputStreamis open or not using thevalid()method on theFileDescriptorinstance obtained by calling thegetFD()method on the ‘FileInputStream’ object:Of course, bear in mind that the Law of Leaky Abstractions applies.