Question

I am struck in this strange problem .

I am using the following method to download files :

public boolean downloadSection(String link,String fileLocation,long currentlyDownloadedBytes){

     try {

                RandomAccessFile file = new RandomAccessFile(fileLocation, "rw");
                file.seek(currentlyDownloadedBytes+1);

                URL imageUrl = new URL(link);
                HttpURLConnection conn  =(HttpURLConnection)imageUrl.openConnection();
                conn.setRequestProperty("Range", "bytes=" + currentlyDownloadedBytes + "-");
                conn.setConnectTimeout(100000);
                conn.setReadTimeout(100000);
                conn.setInstanceFollowRedirects(true);

                InputStream is=conn.getInputStream();
                byte buffer[]=new byte[1024];;
                while (true) {
                    // Read from the server into the buffer
                    int read = is.read(buffer);
                    if (read == -1) {
                        break;
                    }
                   // Write buffer to file
                    file.write(buffer, 0, read);
                 }

                file.close();
                return true;
                } catch (Exception ex){
                      ex.printStackTrace();
                      return false;
                      }

 } 

When i download mp3 file using this code the downloades file opens up well , But a downloaded android app(.apk file) gives Package Parsing Error on opening and an image never opens up .

Please help Thank you

Was it helpful?

Solution

Several things look strange:

a) It looks like you added manually the signature of the method for this question (because link doesn't have a type, so it won't even compile).

b) There are two variables/parameters - alreadyDownloadedBytes and currentlyDownloadedBytes. I assumed it's caused by #a

c) You are doing following

file.seek(currentlyDownloadedBytes+1);

and you should instead do this

file.seek(currentlyDownloadedBytes);

The reason is because you seek to offset. So, as example, if you read just 1 byte, you have to seek to offset 1 (which would be the second byte in file).

d) Check whether any exception are thrown and caught.

e) Where do you update currentlyDownloadedBytes or alreadyDownloadedBytes?

f) My final recommendation would be to debug your application and make sure that the whole file is downloaded

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top