【问题标题】:Android read large files crashing appAndroid读取大文件崩溃应用
【发布时间】:2013-05-18 18:50:40
【问题描述】:

您好,正如您在下面看到的,我正在尝试制作一个(android)应用程序来检查文件的 md5 哈希值 此代码仅适用于小文件 有人可以帮我吗?

final TextView informations = (TextView) findViewById(R.id.Informations);
            final EditText input = (EditText) findViewById(R.id.ToCrack);
            String filepath = data.getDataString();
            String rawtext;
            String hash;
            StringBuilder text = new StringBuilder();
            filepath = filepath.split("//")[1];
            File file = new File(filepath);
            Toast.makeText(getApplicationContext(),"Loading: "+filepath,Toast.LENGTH_LONG).show();
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            DataInputStream dis = null;
            try{
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                dis = new DataInputStream(bis);
                while (dis.available() != 0){
                    text.append(dis.readLine()+"\n");
                }
            }
            catch (IOException e){
                e.printStackTrace();
            }
            finally {
                try{
                    fis.close();
                    bis.close();
                    dis.close();
                }
                catch (IOException ex){
                    ex.printStackTrace();
                }
            }
            rawtext = text.toString().substring(0, text.length()-1);
            hash = new MD5(rawtext).hexdigest();
            if (hash.equals(input.getText().toString())){
                informations.setText("Hash correspond with the file!");
            }
            else{
                informations.setText("File hash= "+hash+"\nHashes does not correspond :(");
            }
            Toast.makeText(getApplicationContext(),"Copied file hash to clipboard.",Toast.LENGTH_LONG).show();

【问题讨论】:

  • 您是否尝试过使用 AsyncTask 在后台线程中读取文件? developer.android.com/reference/android/os/AsyncTask.html
  • 我没试过,但是这段代码直接让应用程序崩溃,所以我猜它不会工作
  • 编辑您的问题并包含堆栈跟踪。
  • 删除available() 测试。您的代码将与while ((line = in.readLine()) != null) 相同。 available() 的正确用法很少,这不是其中之一。

标签: java android io md5 java-io


【解决方案1】:

Android 等移动设备环境在应用程序可以使用的内存量方面存在限制。因此,在您的代码中(使用StringBuffer)将大文件读取到内存数据存储将引发 OutOfMemory 错误。

查看this question,了解如何解决此问题。

【讨论】:

  • 我觉得这很有趣,因为在 android 上使用 python sl4a 我能够非常轻松快速地计算 md5 和东西而不会发生任何崩溃,谷歌花更多时间为 ui 和东西制作 api 而不是简化'应用程序的背景'就像只是打开一个文件......
  • 我对 sl4a 不熟悉,猜想它是在原生应用程序进程中运行的。我想指出,用 SDK(不是 NDK)编写的每个应用程序都运行在它自己的 Dalvik VM 中。
猜你喜欢
  • 1970-01-01
  • 2018-06-18
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多