7

I use a OkHttpClient to download a database on the server and to copy it on my Android application, the request is ok and I get the good content.

However when I try to write my byteStream to my file I get a java.IOException.closed. Do you know what I am doing wrong ?

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);
    }
}

I also tried to read my ByteStream with a BufferedSink but the result was the same

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

StackTrace :

java.io.IOException: closed
    at okio.RealBufferedSource$1.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$2.call(AsyncTask.java:288)
    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
    at android.os.AsyncTask$SerialExecutor$1.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)
2
  • 1
    Could you post your full stack trace please? Commented Oct 28, 2015 at 14:39
  • 1
    Are you using any interceptors that could be closing the stream? Commented Oct 29, 2015 at 1:31

1 Answer 1

9

I find why the stream was closed, for some test, I was checking the content of my output String with a System.out.println, but when you read or print the output it close automatically the stream, this is why I get an error.

In conclusion, One thing to remember with stream : Reading or printing the outputStream will close it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.