当我需要使用它两次时如何重新打开关闭的InputStream
我目前正在使用 InpuStream 从我的服务器获取 JSON 响应。
我需要做两件事:
- 解析它并在屏幕上显示值
- 将此提要保存在 SDCard 文件上
这在一一使用这两种方法时完全没有问题。
解析是用 GSON 进行的:
Gson gson = new Gson();
Reader reader = new InputStreamReader (myInputStream);
Result result = gson.FrmJson(reader, Result.class)
复制到 SDCard 是用 进行的
FileOutputStream f (...) f.write (buffer)
两者都经过测试。
问题是一旦解析完成,我想写入 SDCard,但它中断了。 我知道我的 InputStream 已关闭,这就是问题所在。
这里有一些接近我的问题:How to Cache InputStream for Multiple Use
有没有办法改进该解决方案并提供我们可以使用的东西?
I am currently using an InpuStream to get a JSON response from my server.
I need to do 2 things with:
- Parsing it and displaying the values on the screen
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我可能会使用
ByteArrayOutputStream
将输入流排入byte[]
,然后每次需要时根据结果创建一个新的ByteArrayInputStream
重读流。像这样的东西:
相关且可能有用的问题和答案:
I would probably drain the input stream into a
byte[]
usingByteArrayOutputStream
and then create a newByteArrayInputStream
based on the result every time I need to reread the stream.Something like this:
Related, and possibly useful, questions and answers:
或者,我发现了这个实现它的好方法:
我用
Alternatively, I found this great way to achieve it:
And I call it with