Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reopen a closed InputStream when I need to use it 2 times

I am currently using an InpuStream to get a JSON response from my server.

I need to do 2 things with:

  1. Parsing it and displaying the values on the screen
  2. Save this feed on SDCard file

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?

like image 325
Waza_Be Avatar asked Oct 18 '11 09:10

Waza_Be


1 Answers

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:

  • Multiple readers for InputStream in Java
  • Read stream twice
like image 89
aioobe Avatar answered Oct 11 '22 03:10

aioobe