【问题标题】:How to check if file is existing AND has the same content如何检查文件是否存在并且内容相同
【发布时间】:2014-03-12 08:12:59
【问题描述】:

我在寻找一种方法来了解文件是否存在时遇到了麻烦,如果存在,它是否具有相同的内容?如果是则不下载,否则下载文件。

在我的代码中,我需要先下载 PDF 文件才能查看它。我已经检查文件是否存在,但它只检查文件名(这个我不确定)。 File 类的 exists() 方法是否只检查文件名?如果有,我怎么知道它是否有不同的内容?

这是我的代码:

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);
    }
}

【问题讨论】:

  • 要测试内容是否相等,您可以查看他们的MD5 checksums
  • 感谢您的链接,我刚刚阅读了MD5 checksum 并发现这是解决方案。如果这不是评论,我会接受这个作为答案。

标签: android file file-io android-file


【解决方案1】:

在下载文件之前和之后(以及将其放在 /sdcard 上之后)验证文件的 MD5 checksum 始终是一个好主意。在服务器端正确实施可确保发布托管在那里的文件的 MD5 总和。验证您下载的文件的 MD5 和可确保您拥有完整、完整且未损坏的文件版本。

在您的情况下,您可以将下载并存储在sd-card上的File_1的MD5 checksum与下载前的File_2的MD5 checksum进行比较。

【讨论】:

  • 那很好,但这需要在我的 API 方法中添加返回。现在在APP端,我将检查SD卡中的MD5 checksum和新文件的MD5 checksum
猜你喜欢
  • 2010-11-25
  • 2014-11-05
  • 2021-12-30
  • 1970-01-01
  • 2015-04-28
  • 2017-03-21
  • 2015-09-30
  • 2015-10-26
  • 1970-01-01
相关资源
最近更新 更多