对下载文件是否完整的判断方法

1,使用MD5,本地文件下载完后去文件的md5值与服务器的该文件md5进行比对,一致证明下载完全。

2,比较文件的size,文件长度,下载完成取下File.length,与服务器的文件长度比对,一致则下载完全。
3,文件命名法,开始下载时,把文件命名为宜别名如xxx.tmp,下载完成后再把文件名称修改过来。只要正式的文件名存在,则是下载完全的。
          
          

mMusicSourceFile = new File(MUSIC_FILE_PATH, mCurrentPlayMusic.getMusicName()+".tmp"); //按照SourceFile下载
mMusicDescFile = new File(MUSIC_FILE_PATH, mCurrentPlayMusic.getMusicName());

mClient.downloadFile(new HttpGet(mCurrentPlayMusic.getMusicPath()), mMusicSourceFile)

//下载成功后
mMusicSourceFile.renameTo(mMusicDescFile);

   
         此时,要在download函数中对已下载长度是文件长度否一致进行判断,相当于在download中判断了文件是否下载完全
         
                

int len, mHasRead = 0;
byte[] buffer = new byte[8192];
final long size = response.getEntity().getContentLength();

BufferedOutputStream outputStream = null;
InputStream inputStream = response.getEntity().getContent();
try {
  outputStream = new BufferedOutputStream(new FileOutputStream(mFile));

  while (!Thread.interrupted() && (len = inputStream.read(buffer)) != -1) {
    outputStream.write(buffer, 0, len);
    mHasRead += len;
  }
  outputStream.flush();

  return mHasRead == size;
} finally {
if (outputStream != null)
  outputStream.close();
  if (inputStream != null)
  inputStream.close();
}

原文地址:https://www.cnblogs.com/xxz526/p/3683224.html