Android OkHttp InputStream java.IOException.closed

I use OkHttpClient to load the database on the server and copy it in the Android application, the request is fine, and I get 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 reading my byteStream with 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) 
+5
source share
1 answer

I found why the stream was closed, for some test I checked the contents of my output line with System.out.println , but when you read or print the output, it automatically closes the stream, so I get an error.

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

+3
source

Source: https://habr.com/ru/post/1234710/


All Articles