Android OkHttp InputStream java.IOException.closed

Android OkHttp InputStream java.IOException.closed

我使用 OkHttpClient 在服务器上下载数据库并将其复制到我的 Android 应用程序中,请求正常,我得到了很好的内容。

然而,当我尝试将 byteStream 写入我的文件时,我得到了 java.IOException.closed。你知道我做错了什么吗?

Response httpResponse = webApiClient.execute(
    new WebApiRequest(WebApiMethod.DB_DOWNLOAD), context);

if (httpResponse.code() == 200)
{
    try 
    {
        InputStream inputStream = httpResponse.body().byteStream();
        File databasePath = context.getDatabasePath(Constant.DATABASE_NAME);
        FileOutputStream output = new FileOutputStream(databasePath);
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];
        int len;
        while ((len = inputStream.read(buffer)) != -1)
        {
            output.write(buffer, 0, len);
        }
        success = true;
    }
    catch (Exception exc)
    {
        Utils.DisplayException(exc, context);
    }
}

我也尝试用 BufferedSink 阅读我的 ByteStream 但结果是一样的

BufferedSink sink = Okio.buffer(Okio.sink(databasePath));
sink.writeAll(httpResponse.body().source());
sink.close();

堆栈跟踪:

java.io.IOException: closed
    at okio.RealBufferedSource.read(RealBufferedSource.java:367)
    at java.io.InputStream.read(InputStream.java:162)
    at com.org.dbconn.LoginActivity$DbDownloadTask.doInBackground(LoginActivity.java:475)
    at com.org.dbconn.LoginActivity$DbDownloadTask.doInBackground(LoginActivity.java:436)
    at android.os.AsyncTask.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:231)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
    at java.lang.Thread.run(Thread.java:818)

我找到了关闭流的原因,为了进行一些测试,我用 System.out.println 检查输出字符串的内容,但是当您读取或打印输出时,它会自动关闭流,这是为什么我得到一个错误。

总之, 使用 stream 需要记住一件事:读取或打印 outputStream 将关闭它。