I am currently using an InpuStream to get a JSON response from my server.
I need to do 2 things with:
That gives me no issues at all when using these 2 methods one by one.
The parsing is made with GSON:
Gson gson = new Gson();
Reader reader = new InputStreamReader (myInputStream);
Result result = gson.FrmJson(reader, Result.class)
and the copy to SDCard is made with
FileOutputStream f (...) f.write (buffer)
Both of them have been tested.
TYhe problem is once the parsing is done, I want to write to SDCard and it breaks. I understand that my InputStream is closed, and that's the issue.
There is something close to my question here: How to Cache InputStream for Multiple Use
Is there a way to improve that solution and provide something that we can use?
I would probably drain the input stream into a byte[]
using ByteArrayOutputStream
and then create a new ByteArrayInputStream
based on the result every time I need to reread the stream.
Something like this:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while ((n = myInputStream.read(buf)) >= 0)
baos.write(buf, 0, n);
byte[] content = baos.toByteArray();
InputStream is1 = new ByteArrayInputStream(content);
... use is1 ...
InputStream is2 = new ByteArrayInputStream(content);
... use is2 ...
Related, and possibly useful, questions and answers:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With