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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With