1

I uploaded a JAR file that was 21 KB in size on my computer to a website. I found the direct link to that JAR file and I create an InputStream to that file:

URL url = new URL("addresstofile");
InputStream stream = url.openStream();

It would be expected that the amount of bytes available in the stream would be ~21,000. However, the amount available is 7,048. In an attempt to debug, I saved those 7,048 bytes in a byte array and then I write those bytes to a temporary file with the extension ".jar"

I extract the classes in the JAR file (that is 7 KB; the original is 21 KB). Most of the classes are there except I noticed that nested classes are not present. I am not sure as to why that is - is it just a coincidence that the InputStream just cuts out there, or are there some special exceptions to nested classes?

Why is InputStream acting so oddly? Thanks!

@Neil: This works! Thanks a lot!

1
  • The stream only ends when a call to read() returns -1. Ignore the available() method. It's really not useful for much. Commented Mar 4, 2012 at 22:13

3 Answers 3

2

In the modified version of the code you present, the problem is the comparison. Don't cast 'b' to an int before making the comparison with -1. If you do that then if a byte in the stream happens to be 255, you won't be able to differentiate between this byte and the end of the stream.

So make the comparison with -1 on the int returned from read(). Then if it's not -1, cast the value to a byte and put it in the array (or whatever).

int b;
while ((b = stream.read()) != -1)
{
    data[length++] = (byte) b;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Calling available() on an input stream tells you how many bytes can be read right now - for network I/O isn't necessarily the whole file, most likely what is just buffered in local socket. Loop and keep trying.

Comments

0

It would be expected that the amount of bytes available in the stream would be ~21,000

Why?

How can you possibly know that the number of bytes available to be read without blocking was 21,000?

2 Comments

Because the file was 21 KB on my computer.
@MartinTuskevicius So? How do you know the I/O system can read all that without blocking? My question was intended to get you thinking about the actual definition of the available() method, and to realize that it isn't specified to return the total length of the stream. Indeed there is a specific warning about that in the Javadoc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.