2

I'm having trouble of looking for a way to know whether a file exists, if it does, does it have the same content? If yes then don't download, otherwise download the file.

In my code, I need to download the PDF file before viewing it. I have already the checking if file exists, but it checks only the filename (this one I'm not sure of). Does the File class' exists() method only check for filename? If it does, how do I know if it has different content?

Here's my code:

class DownloadFileTask extends AsyncTask<String, String, String> {
    private Context context;
    public ProgressDialog pDialog;
    private File pdfFile = new File(Environment
            .getExternalStorageDirectory().getPath()
            + "/SAMPLE/"
            + pdfFileName);

    public DownloadFileTask(Context context) {
        this.context = context;
    }

    /**
     * Before starting background thread Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        if (!pdfFile.exists()) {
            pDialog = new ProgressDialog(context);
            pDialog.setMessage(getString(R.string.loading));
            pDialog.setCancelable(false);
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.show();
        }
    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... path) {
        int count;

        if (!pdfFile.exists()) {
            if (Utility.isNetworkAvailable(parentActivityContext)) {
                try {
                    String urlLastPath = Utility
                            .getLastPathFromUrl(path[0]);

                    String urlEncoded = URLEncoder.encode(urlLastPath,
                            "utf-8");

                    String urlDecoded = null;
                    String urlStr;
                    if (urlEncoded.contains(" ")) {
                        urlDecoded = urlEncoded.replaceAll(" ", "%20");
                        urlStr = SystemInfo.getResourceUrl() + "pdf/"
                                + urlDecoded;
                    } else if (urlEncoded.contains("+")) {
                        urlDecoded = urlEncoded.replaceAll(
                                Pattern.quote("+"), "%20");
                        urlStr = SystemInfo.getResourceUrl() + "pdf/"
                                + urlDecoded;
                    } else {
                        urlStr = SystemInfo.getResourceUrl() + "pdf/"
                                + urlEncoded;
                    }

                    URL url = new URL(urlStr);

                    URLConnection urlConnection = url.openConnection();
                    urlConnection.connect();
                    // getting file length
                    int lengthOfFile = urlConnection.getContentLength();

                    // input stream to read file - with 8k buffer
                    InputStream input = new BufferedInputStream(
                            url.openStream(), 8192);

                    // Output stream to write file
                    OutputStream output = new FileOutputStream(Environment
                            .getExternalStorageDirectory().getPath()
                            + "/'SAMPLE/" + pdfFileName);

                    byte data[] = new byte[1024];

                    long total = 0;

                    while ((count = input.read(data)) != -1) {
                        total += count;
                        // publishing the progress....
                        // After this onProgressUpdate will be called
                        publishProgress(""
                                + (int) ((total * 100) / lengthOfFile));

                        // writing data to file
                        output.write(data, 0, count);
                    }

                    // flushing output
                    output.flush();

                    // closing streams
                    output.close();
                    input.close();

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("Error: ", e.getMessage());
                }
            } else {
                openDialog(getString(R.string.error),
                        getString(R.string.internet_connection_error));
            }
        }
        return null;
    }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }

        /** PDF reader code */
        Intent intent = new Intent(parentActivityContext,
                MuPDFActivity.class);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.fromFile(pdfFile));
        startActivity(intent);
    }
}
Compaq LE2202x
  • 2,030
  • 9
  • 45
  • 62
  • 3
    To test for content equality, you could check their [MD5 checksums](http://stackoverflow.com/questions/13152736/how-to-generate-an-md5-checksum-for-a-file-in-android) – CodingIntrigue Mar 12 '14 at 08:16
  • Thanks for the link, I just read about `MD5 checksum` and found out this was the solution. If this wasn't a comment, I'd accept this as an answer. – Compaq LE2202x Mar 12 '14 at 08:55

1 Answers1

1

Its always a good idea to validate a file's MD5 checksum before and after you download it (and after placing it on your /sdcard). Proper implementation at server side makes sure that the MD5 sums for the files hosted there are published. Verifying the MD5 sum of the file that you've downloaded ensures that you have a full, complete, and uncorrupted version of the file.

In your case, you can compare the MD5 checksum of the File_1 after downloading and storing it on sd-card with the MD5 checksum of File_2 before downloading.

Ritesh Gune
  • 16,629
  • 6
  • 44
  • 72
  • That'd be nice, but that'd require adding return to my API method. For now in the APP side, I will check the `MD5 checksum` in the SD card with the `MD5 checksum` of the new file. – Compaq LE2202x Mar 12 '14 at 08:54