2015-01-03 5 views
0

내 시나리오에서는 애셋에서 압축 된 외부 읽기 전용 db를 사용하고 초기 실행시 내부 저장소로 복사/복사합니다.안드로이드 파일 복사 완전성 확인

사용자 장치가 디스크에 충분한 메모리가 없으면 복사를 완료 할 때 문제가 발생합니다.

이전에 사용 가능한 공간을 확인했지만 안드로이드 OS 자체는 RAM이 부족할 때 가상 메모리/페이지 파일을 사용하므로 여유 MB 수가 일정하지 않습니다.

파일 자체가 완성되었는지 확인하는 방법을 찾고 싶습니다.이를 수행하는 방법은 무엇입니까?

답변

1

파일이 일치하는지 확인하는 것은 두 파일의 MD5 해시가 서로 일치하면 항상 확인합니다.

당신은 당신이 파일의 당신의 MD5 해시를 미리 계산하고 새로운 옮겨진 파일과 일치하는 경우 바로 확인해야합니다 꽤 잘 https://github.com/CyanogenMod/android_packages_apps_CMUpdater/blob/cm-10.2/src/com/cyanogenmod/updater/utils/MD5.java

/* 
* Copyright (C) 2012 The CyanogenMod Project 
* 
* * Licensed under the GNU GPLv2 license 
* 
* The text of the license can be found in the LICENSE file 
* or at https://www.gnu.org/licenses/gpl-2.0.txt 
*/ 

package com.cyanogenmod.updater.utils; 

import android.text.TextUtils; 
import android.util.Log; 

import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 
import java.io.InputStream; 
import java.math.BigInteger; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 

public class MD5 { 
    private static final String TAG = "MD5"; 

    public static boolean checkMD5(String md5, File updateFile) { 
     if (TextUtils.isEmpty(md5) || updateFile == null) { 
      Log.e(TAG, "MD5 string empty or updateFile null"); 
      return false; 
     } 

     String calculatedDigest = calculateMD5(updateFile); 
     if (calculatedDigest == null) { 
      Log.e(TAG, "calculatedDigest null"); 
      return false; 
     } 

     Log.v(TAG, "Calculated digest: " + calculatedDigest); 
     Log.v(TAG, "Provided digest: " + md5); 

     return calculatedDigest.equalsIgnoreCase(md5); 
    } 

    public static String calculateMD5(File updateFile) { 
     MessageDigest digest; 
     try { 
      digest = MessageDigest.getInstance("MD5"); 
     } catch (NoSuchAlgorithmException e) { 
      Log.e(TAG, "Exception while getting digest", e); 
      return null; 
     } 

     InputStream is; 
     try { 
      is = new FileInputStream(updateFile); 
     } catch (FileNotFoundException e) { 
      Log.e(TAG, "Exception while getting FileInputStream", e); 
      return null; 
     } 

     byte[] buffer = new byte[8192]; 
     int read; 
     try { 
      while ((read = is.read(buffer)) > 0) { 
       digest.update(buffer, 0, read); 
      } 
      byte[] md5sum = digest.digest(); 
      BigInteger bigInt = new BigInteger(1, md5sum); 
      String output = bigInt.toString(16); 
      // Fill to 32 chars 
      output = String.format("%32s", output).replace(' ', '0'); 
      return output; 
     } catch (IOException e) { 
      throw new RuntimeException("Unable to process file for MD5", e); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       Log.e(TAG, "Exception on closing MD5 input stream", e); 
      } 
     } 
    } 
} 

작동합니다 github.This의 사이 애 노젠 모드의 ROM 저장소에서이 클래스를 사용할 수 있습니다

.