android sd卡缓存

1、通过url下载内容到sd卡中的download的文件夹里面,并把路径加入到cache的缓存里。
2、删除你下载的所有文件和文件夹
3、下载使用的是okHttp

上代码

import android.os.Environment;
import android.support.v4.util.LruCache;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownLoader {

    final String filename = "YiCache";  // 保存的文件名
    private LruCache pathLruCache;

    private static DownLoader Instance;

    private DownLoader() {
    }

    public static DownLoader getInstance() {
        if (Instance == null) {
            synchronized (DownLoader.class) {
                Instance = new DownLoader();
            }
        }

        return Instance;
    }
  //  清空下载的文件夹并包括里面的文件
    public void clean() {
        if (pathLruCache != null) {
            deleteFile(filename);
            pathLruCache.evictAll();
        }
    }

//  将下载的内容的sd卡路径保存到cache中
    void addCacheData(String url, String data) {
        if (pathLruCache == null) {
            int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
            int cacheSize = maxMemory / 8;
            pathLruCache = new LruCache(cacheSize);
        }

        if (data != null) {
            pathLruCache.put(url, data);
        }
    }

//  开始下载
    public void prepareResourcse(final String url, final DownLoadOKCallback listener) {

        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败
                Log.v("Yi+", "下载失败  ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = isExistDir(filename);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    File file = new File(savePath, getNameFromUrl(url));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
//                            listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    addCacheData(url,file.getAbsolutePath());
                    Log.v("Yi+", "储存下载文件的目录  " + file.getAbsolutePath());
                    if (listener != null) {
                        listener.onDownloadSuccess();
                    }

                } catch (Exception e) {
                    Log.v("Yi+", "下载失败  " + e.getMessage());
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * @param url
     * @return 从下载连接中解析出文件名
     */
    private String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

/ /  建立下载文件夹
    private String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }

    private void deleteFile(String saveDir) {
        File downloadFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), saveDir);
        if (downloadFile.exists()) {
            RecursionDeleteFile(downloadFile);
        }
    }

    private static void RecursionDeleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                RecursionDeleteFile(f);
            }
            file.delete();
        }
    }

// 根据url获得下载的文件的路径
    public String getGifCacheData(String url) {
        return pathLruCache.get(url);
    }

你可能感兴趣的:(android sd卡缓存)