Reputation: 747
I have an object of StreamResource class w/ some needed content in it. I'm sure this content is valid and i need to save it locally for the further processing. Here is the code snippet:
OutputStream os = new FileOutputStream(filePath, false);
byte[] buffer = new byte[1024];
int bytesRead;
//read from is to buffer
try {
while(true)
{
bytesRead = resource.getStream().getStream().read(buffer);
if(bytesRead == -1)
break;
os.write(buffer, 0, bytesRead);
resource.getStream().getStream().skip(bytesRead);
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
And here i join the endless loop. Break is never ocured and file in the needed location becomes huge as it should actually. Under debugger i see that read() operation returns only the 1st chunk of bytes in each iteration even w/ skip() call after os.write.
How should i read the content from the stream?
Thanks.
Upvotes: 0
Views: 959
Reputation: 2749
According to the source code of StreamResource a new DownloadStream is created on each call. You should call it only once like in the following snippet:
OutputStream os = new FileOutputStream(filePath, false);
byte[] buffer = new byte[1024];
int bytesRead;
//read from is to buffer
try {
DownloadStream stream = resource.getStream();
while(true)
{
bytesRead = stream.getStream().read(buffer);
if(bytesRead == -1)
break;
os.write(buffer, 0, bytesRead);
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
That way the stream will not be read from the beginning on every iteration. However, I still don't get why you use the indirection over StreamResource because I guess you create that object before.
Upvotes: 1