问题描述
我目前使用的是InpuStream让从我的服务器JSON响应。
I am currently using an InpuStream to get a JSON response from my server.
我需要做两件事情有:
- 解析它,并在屏幕上显示的值
- 在保存此饲料SD卡上的文件
使用这2种方法一一当这给了我没有问题的。
That gives me no issues at all when using these 2 methods one by one.
解析是用GSON:
Gson gson = new Gson();
Reader reader = new InputStreamReader (myInputStream);
Result result = gson.FrmJson(reader, Result.class)
和复制到SD卡是用
FileOutputStream f (...) f.write (buffer)
他们都进行了检验。
Both of them have been tested.
TYhe问题是,一旦解析完成后,我想写入SD卡,它打破了。据我所知,我的InputStream是封闭的,这是个问题。
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.
也有一些是接近我的问题在这里:如何缓存的InputStream的多使用
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?
推荐答案
我可能会漏输入流成字节[]
使用 ByteArrayOutputStream
,然后创建我需要重读流了新的 ByteArrayInputStream的
根据该结果每一次。
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.
事情是这样的:
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 ...
这篇关于我怎样才能重新打开已关闭的InputStream,当我需要使用它的2倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!