当我需要使用2次关闭的输入流时,如何重新打开它

2022-09-02 20:37:54

我目前正在使用 InpuStream 从我的服务器获取 JSON 响应。

我需要做2件事:

  1. 解析并在屏幕上显示值
  2. 将此提要保存在SD卡文件上

在逐个使用这些2方法时,这完全没有问题。

解析是使用GSON进行的:

Gson gson = new Gson();
Reader reader = new InputStreamReader (myInputStream);
Result result = gson.FrmJson(reader, Result.class)

并且复制到SD卡是用

FileOutputStream f (...) f.write (buffer)

它们都经过测试。

TYhe问题是,一旦解析完成,我想写到SDCard,它就会中断。我知道我的输入流已关闭,这就是问题所在。

这里有一些接近我的问题:如何缓存输入流以供多种使用

有没有办法改进该解决方案并提供我们可以使用的东西?


答案 1

我可能会将输入流排出到一个 using 中,然后在每次需要重新读取流时根据结果创建一个新的。byte[]ByteArrayOutputStreamByteArrayInputStream

像这样:

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 ...

相关且可能有用的问题和答案:


答案 2

或者,我发现了这个实现它的好方法:

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class CopyInputStream
{
    private InputStream _is;
    private ByteArrayOutputStream _copy = new ByteArrayOutputStream();

    /**
     * 
     */
    public CopyInputStream(InputStream is)
    {
        _is = is;

        try
        {
            copy();
        }
        catch(IOException ex)
        {
            // do nothing
        }
    }

    private int copy() throws IOException
    {
        int read = 0;
        int chunk = 0;
        byte[] data = new byte[256];

        while(-1 != (chunk = _is.read(data)))
        {
            read += data.length;
            _copy.write(data, 0, chunk);
        }

        return read;
    }

    public InputStream getCopy()
    {
        return (InputStream)new ByteArrayInputStream(_copy.toByteArray());
    }
}

我称之为

CopyInputStream cis = new CopyInputStream(input);
InputStream input1 = cis.getCopy();

推荐