欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android緩存之DiskLruCache磁盤(pán)緩存的使用

 更新時(shí)間:2018年08月28日 13:44:16   作者:大熊啊啊啊  
這篇文章主要介紹了Android緩存之DiskLruCache磁盤(pán)緩存的使用,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

DiskLruCache和LruCache不同的是,LruCache是內(nèi)存緩存,而DiskLruCache是指磁盤(pán)緩存,顧名思義就是把文件緩存到磁盤(pán),也也就是手機(jī)的內(nèi)存卡中。接下來(lái)先簡(jiǎn)單介紹DiskLruCache的使用方法。

下載源碼

DiskLruCache并沒(méi)有在 SDK中存在,但又是谷歌提倡的。所以我們要先把DiskLruCache的源碼下載下來(lái)。
我們可以通過(guò)下面這個(gè)地址下載源碼:https://github.com/JakeWharton/DiskLruCache/tree/master/src/main/java/com/jakewharton/disklrucache

然后把源碼中的三個(gè)類拷貝到工程中。

DiskLruCache常用方法:

方法 備注
DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize) 打開(kāi)一個(gè)緩存目錄,如果沒(méi)有則首先創(chuàng)建它,directory:指定數(shù)據(jù)緩存地址 appVersion:APP版本號(hào),當(dāng)版本號(hào)改變時(shí),緩存數(shù)據(jù)會(huì)被清除 valueCount:同一個(gè)key可以對(duì)應(yīng)多少文件 maxSize:最大可以緩存的數(shù)據(jù)量
Editor edit(String key) 通過(guò)key可以獲得一個(gè)DiskLruCache.Editor,通過(guò)Editor可以得到一個(gè)輸出流,進(jìn)而緩存到本地存儲(chǔ)上
void flush() 強(qiáng)制緩沖文件保存到文件系統(tǒng)
Snapshot get(String key) 通過(guò)key值來(lái)獲得一個(gè)Snapshot,如果Snapshot存在,則移動(dòng)到LRU隊(duì)列的頭部來(lái),通過(guò)Snapshot可以得到一個(gè)輸入流InputStream
long size() 緩存數(shù)據(jù)的大小,單位是byte
boolean remove(String key) 根據(jù)key值來(lái)刪除對(duì)應(yīng)的數(shù)據(jù),如果該數(shù)據(jù)正在被編輯,則不能刪除
void delete() 關(guān)閉緩存并且刪除目錄下所有的緩存數(shù)據(jù),即使有的數(shù)據(jù)不是由DiskLruCache 緩存到本目錄的
void close() 關(guān)閉DiskLruCache,緩存數(shù)據(jù)會(huì)保留在外存中
boolean isClosed() 判斷DiskLruCache是否關(guān)閉,返回true表示已關(guān)閉
File getDirectory() 緩存數(shù)據(jù)的目錄

初始化緩存對(duì)象

接下來(lái)具體介紹DiskLruCache的簡(jiǎn)單方法。首先我們?cè)谑褂媚硞€(gè)類的時(shí)候,一般都是首先找到它的構(gòu)造方法,但是我們發(fā)現(xiàn)該類是final 類,無(wú)法被繼承,并且構(gòu)造方法是私有的方法,不能手動(dòng)調(diào)用。

public final class DiskLruCache implements Closeable {

 private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
  this.directory = directory;
  this.appVersion = appVersion;
  this.journalFile = new File(directory, JOURNAL_FILE);
  this.journalFileTmp = new File(directory, JOURNAL_FILE_TEMP);
  this.journalFileBackup = new File(directory, JOURNAL_FILE_BACKUP);
  this.valueCount = valueCount;
  this.maxSize = maxSize;
 }

所以在初始化DiskLruCache的時(shí)候調(diào)用它的open方法

 //四個(gè)參數(shù)分別為,1.緩存的路徑目錄 2.版本號(hào) 3.每個(gè)節(jié)點(diǎn)對(duì)應(yīng)的數(shù)據(jù)個(gè)數(shù),4.緩存的大小,10 * 1024 * 1024 = 10M
      DiskLruCache diskLruCache = DiskLruCache.open(getCachFile(context, uniqueName), 1, 1, cacheSize);

/**
   * 獲取緩存目錄
   *
   * @param context
   * @param uniqueName 指定目錄下的文件名
   */
  private File getCachFile(Context context, String uniqueName) {
    String catchPath;
    //有內(nèi)存卡,并且內(nèi)存卡沒(méi)有正在移除,就把文件緩存到內(nèi)存卡中
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable()) {
      catchPath = context.getExternalCacheDir().getPath();
    } else {
      catchPath = context.getCacheDir().getPath();
    }
    return new File(catchPath + File.separator + uniqueName);
  }

要傳入四個(gè)參數(shù):

  • File directory:sdcard緩存的目錄。
  • int appVersion:版本號(hào),一般傳1即可
  • int valueCount:緩存的數(shù)據(jù)由key對(duì)應(yīng)著,表示一個(gè)key對(duì)應(yīng)多少個(gè)數(shù)據(jù),一般傳1即可
  • long maxSiz:緩存的大小 10 * 1024 * 1024 = 10M

傳入sdcard緩存的目錄的時(shí)候,記得先判斷sdcard是否存在,或者sdcard是否正在移除。如果是這兩種情況。緩存目錄就設(shè)置為getCacheDir().getPath();在內(nèi)存中緩存。

寫(xiě)入緩存

初始化緩存完成之后,就寫(xiě)入緩存,這個(gè)時(shí)候需要從網(wǎng)上下載一張圖片。

new Thread() {
          @Override
          public void run() {
            DiskLruCache.Editor editor = null;
            try {
              //創(chuàng)建 Editor 對(duì)象
              editor = diskLruCache.edit(hashKeyForDisk(url));
              if (editor != null) {
                //創(chuàng)建輸出流
                OutputStream outputStream = editor.newOutputStream(0);
                //url 也就是 下載圖片的地址
                //outputStream 的作用在于,
                //從網(wǎng)絡(luò)下載圖片的時(shí)候,圖片通過(guò)該輸出流寫(xiě)到文件系統(tǒng),
                //也就是說(shuō),圖片下載到了磁盤(pán)緩存中。
                if (downloadUrlToStream(url, outputStream)) {
                  editor.commit();
                } else {
                  //釋放編輯鎖
                  editor.abort();
                }
                diskLruCache.flush();
              }

            } catch (Exception e) {
              e.printStackTrace();
            }

          }
        }.start();

 /**
   * 將key進(jìn)行加密
   *
   * @param key
   * @return
   */
  public String hashKeyForDisk(String key) {
    String cacheKey;
    try {
      final MessageDigest mDigest = MessageDigest.getInstance("MD5");
      mDigest.update(key.getBytes());
      cacheKey = bytesToHexString(mDigest.digest());
    } catch (NoSuchAlgorithmException e) {
      cacheKey = String.valueOf(key.hashCode());
    }
    return cacheKey;
  }

  private String bytesToHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
      String hex = Integer.toHexString(0xFF & bytes[i]);
      if (hex.length() == 1) {
        sb.append('0');
      }
      sb.append(hex);
    }
    return sb.toString();
  }

我們首先初始化 DiskLruCache.Editor editor對(duì)象,把圖片的url經(jīng)過(guò)MD5加密,然后作為緩存圖片的key。這里為什么不直接用url作為key而要進(jìn)行md5加密呢。因?yàn)閡rl中,可能存在一些特殊字符,這樣一來(lái)可能在命名文件的時(shí)候不合法。 md5加密之后的字符是唯一的,并且都是0-F的字符。然后創(chuàng)建OutputStream outputStream對(duì)象

OutputStream outputStream = editor.newOutputStream(0);

下載圖片之后就是通過(guò)該輸出流進(jìn)行寫(xiě)入文件,也就是說(shuō),把下載下來(lái)的圖片寫(xiě)入到緩存目錄中。

 //也就是說(shuō),圖片下載到了磁盤(pán)緩存中。
                if (downloadUrlToStream(url, outputStream)) {
                  editor.commit();
                } else {
                  //釋放編輯鎖
                  editor.abort();
                }
                diskLruCache.flush();

下載成功后調(diào)用 editor.commit();提交即可。

我們具體看下下載圖片的方法

/**
   * 從網(wǎng)絡(luò)中下載圖片,并寫(xiě)到緩存中
   *
   * @param urlString
   * @param outputStream
   * @return
   */
  private boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
      final URL url = new URL(urlString);
      urlConnection = (HttpURLConnection) url.openConnection();
      in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
      out = new BufferedOutputStream(outputStream, 8 * 1024);
      int b;
      while ((b = in.read()) != -1) {
        out.write(b);
      }
      return true;
    } catch (final IOException e) {
      e.printStackTrace();
    } finally {
      if (urlConnection != null) {
        urlConnection.disconnect();
      }
      try {
        if (out != null) {
          out.close();
        }
        if (in != null) {
          in.close();
        }
      } catch (final IOException e) {
        e.printStackTrace();
      }
    }
    return false;
  }

我們看到下載的圖片寫(xiě)到 OutputStream outputStream中,也就是寫(xiě)到了緩存中。這樣一來(lái)就把圖片寫(xiě)到了緩存中了。
我們看下緩存圖片的目錄:

我們看到這里有一個(gè)journal文件和一個(gè)名字很長(zhǎng)的文件,名字很長(zhǎng)的文件,就是我們的緩存文件了,因?yàn)槭墙?jīng)過(guò)md5加密后的字符串。

讀取緩存

接下里我們介紹如何讀取緩存文件。

 DiskLruCache.Snapshot snapshot = diskLruCache.get(hashKeyForDisk(url));
        if(snapshot!=null){
          InputStream inputStream = snapshot.getInputStream(0);
          Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
          //如果不為空,則直接展示緩存中的bitmap
          imageView.setImageBitmap(bitmap); 
        }

這里為什么是getInputStream(0);呢。因?yàn)槲覀兩厦娑x了一個(gè)key對(duì)應(yīng)一個(gè)數(shù)據(jù),所以只獲取第0個(gè)即可
我們看下運(yùn)行的效果圖:


移除緩存

調(diào)用remove方法,移除指定的數(shù)據(jù)。

public synchronized boolean remove(String key) throws IOException 

其他api

1.flush()

用于將內(nèi)存中的操作記錄同步到日志文件,也就是sdcard中的journal文件。DiskLruCache正常工作就要依賴該文件中的內(nèi)容。但是沒(méi)必要每次寫(xiě)入緩存操作的時(shí)候都調(diào)用一次,一般在Activity的onPause方法中調(diào)用一次即可。

2.delete()

刪除所有的緩存

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論