Copying Files In Android With Input/output Stream: The Good And The Bad Way
Solution 1:
The problem lies in your for loop checking the condition after the first run through. Basically the error occurs when it has read fine the last loop but on the next loop the is.read
call returns -1. Afterwards you try to call os.write(bytes,0,-1); -1 is an invalid index. The solution would be:
publicvoidCopyStream(long size, InputStream is, OutputStream os) {
final int buffer_size = 4096;
try {
byte[] bytes = newbyte[buffer_size];
for (int count=0,prog=0;count!=-1;) {
count = is.read(bytes);
if(count != -1) {
os.write(bytes, 0, count);
prog=prog+count;
publishProgress(((long) prog)*100/size);
}
}
os.flush();
is.close();
os.close();
} catch (Exception ex) {
Log.e(TAG,"CS "+ex);
}
}
But it is much more readable as the while loop so I would stick with that. For loops should be used either when you know the quantity of times to loop or as a for each where you loop through each individual item of a collection.
Solution 2:
For loop stop condition is checked before calling is.read()
. This allow situation when you try to read bytes, get result in -1 value and try to continue executing for loop code. While stops immediately after is.read()
returns -1
Try following:
int count = is.read(bytes);
for (prog=0;count!=-1;) {
os.write(bytes, 0, count);
prog=prog+count;
publishProgress(((long) prog)*100/size);
count = is.read(bytes);
}
Solution 3:
privatestaticfinalintBASE_BUFFER_SIZE=4096;
publicstaticvoidcopyFile(InputStream inputStream, OutputStream outputStream)throws IOException {
byte[] bytes = newbyte[BASE_BUFFER_SIZE];
int count;
while ((count = inputStream.read(bytes)) != -1){
outputStream.write(bytes, 0, count);
}
close(inputStream);
close(outputStream);
}
publicstaticvoidclose(@Nullable OutputStream stream) {
if (stream != null) {
try {
stream.flush();
} catch (IOException ignored) {
}
try {
stream.close();
} catch (IOException ignored) {
}
}
}
publicstaticvoidclose(@Nullable InputStream stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException ignored) {
}
}
}
Post a Comment for "Copying Files In Android With Input/output Stream: The Good And The Bad Way"