[英]InputStream for Objects from HttpURLConnection Not Getting All Data
So I have an HttpURLConnection connecting to some image on some URL. 所以我有一个HttpURLConnection连接到某些URL上的某些图像。 I am downloading this image using the Range property (downloading one file in separate parallel connections).
我正在使用Range属性下载此图像(在单独的并行连接中下载一个文件)。 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).
除非我尝试对一个更大的文件进行InputStream,否则一切都会很好地工作(这意味着我可以通过200个并行连接获取文件,但不能以5个并行连接获取文件)。
For example: 例如:
Say I want to download the object: http://stuorgs.uga.edu/images/spotlight/spotlight_button.png in just 1 part. 假设我要下载对象: http : //stuorgs.uga.edu/images/spotlight/spotlight_button.png仅1部分。 So my range is from bytes=0-max.
所以我的范围是从字节= 0-最大。 My program creates a byte array of size max, and the InputStream from the HttpURLConnection is read into the array.
我的程序创建了一个最大大小为字节的字节数组,并将HttpURLConnection的InputStream读入该数组。 However, the InputStream, after a certain point, either only sends over 0000, or closes prematurely.
但是,在特定点之后,InputStream要么仅发送0000以上,要么过早关闭。
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? 那么,我的InputStream是否提早关闭? 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. Javadoc中没有任何地方声明
InputStreamread(byte[])
填充了缓冲区。 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()
. 或使用
DataInputStream.readFully()
。
NB Don't name your variables after classes, and don't start the names with capital letters. 注意:不要在课后命名变量,也不要以大写字母开头。 That's for classes.
那是上课的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.