Incomplete file downloaded in android using DataInputStream

221 views Asked by At

I am having a large file about 90 MB on server and its .mp3 file I am downloading it using this code in android

            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            int contentLength = conexion.getContentLength();
            InputStream is = url.openStream();
            DataInputStream dis = new DataInputStream(is);
            byte[] buffer = new byte[1024];
            int length;
            FileOutputStream fos = new FileOutputStream(new File(
                    Environment.getExternalStorageDirectory() + "/"
                            + aurl[1]));
            long total = 0;
            while ((length = dis.read(buffer)) > 0) {
                total += length;
                publishProgress("" + (int) ((total * 100) / contentLength));
                fos.write(buffer, 0, length);
            }
            is.close();
            fos.close();
            dis.close();

but the problem is sometime in fact most of the time it skips content and not download complete file and postexecute is called. I want you get some helpful suggestion how to make sure complete file is downloaded and show the downloading progress bar until complete content is downloaded.

Also does it matter if we use byte array size increase from 1024 to some multiple of it ?

 byte data[] = new byte[4096];
1

There are 1 answers

0
NazarK On

I do not know certainly but try to use that condition

while ((length = dis.read(buffer)) != -1) { }

There could be the moments when we read 0 bytes, but it does not mean that it is the end of the stream