So I have an HttpURLConnection connecting to some image on some URL. I am downloading this image using the Range property (downloading one file in separate parallel connections). After I grab all of the parts, I stitch them back together. Everything works great unless I try to do an InputStream with a larger file (meaning that I can get a file in 200 parallel connections, but not 5).
For example:
Say I want to download the object: http://stuorgs.uga.edu/images/spotlight/spotlight_button.png in just 1 part. So my range is from bytes=0-max. My program creates a byte array of size max, and the InputStream from the HttpURLConnection is read into the array. However, the InputStream, after a certain point, either only sends over 0000, or closes prematurely.
Here is my code:
try {
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
String bytesToGrab = "bytes=" + startingByte + "-" + endingByte;
urlConnection.setRequestProperty("Range", bytesToGrab);
int sizeOfData = endingByte - startingByte;
byte[] storeData = new byte[sizeOfData];
InputStream inputStream = urlConnection.getInputStream();
inputStream.read(storeData);
inputStream.close();
createFile(storeData); // this takes the byte array and creates a file with it
} catch (IOException e) {
System.out.println("Cannot open url connection: " + e);
}
So, is my InputStream closing early? If so, how do I prevent that from happening? Otherwise, what is wrong?
Nowhere in the Javadoc does it state that InputStreamread(byte[])
fills the buffer. It blocks until at least one byte of data is available and then transfers whatever is available, and returns a count of bytes transferred.
You have to loop. Or use DataInputStream.readFully()
.
NB Don't name your variables after classes, and don't start the names with capital letters. That's for classes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.