CacheUtils.java 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package com.benyanyi.okhttp.util;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.os.Environment;
  5. import com.benyanyi.okhttp.OkHttpUtil;
  6. import java.io.BufferedReader;
  7. import java.io.BufferedWriter;
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.FileReader;
  11. import java.io.OutputStreamWriter;
  12. /**
  13. * @author myLove
  14. */
  15. public final class CacheUtils {
  16. private static File realFile;
  17. @SuppressLint("StaticFieldLeak")
  18. private static Context mContext;
  19. @SuppressLint("StaticFieldLeak")
  20. private static CacheUtils instance;
  21. public static CacheUtils getInstance(Context context) {
  22. if (instance == null) {
  23. instance = new CacheUtils();
  24. mContext = context;
  25. }
  26. if (OkHttpUtil.cacheFile == null) {
  27. File dir = mContext.getExternalFilesDir(null);
  28. if (dir != null && !dir.exists() && Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
  29. dir.mkdirs();
  30. } else {
  31. dir = mContext.getFilesDir();
  32. if (!dir.exists()) {
  33. dir.mkdirs();
  34. }
  35. }
  36. realFile = dir;
  37. } else {
  38. realFile = OkHttpUtil.cacheFile;
  39. }
  40. return instance;
  41. }
  42. /**
  43. * 根据url的MD5作为文件名,进行缓存
  44. *
  45. * @param url 文件名
  46. * @param json
  47. */
  48. public void setCacheToLocalJson(String url, String json) {
  49. String urlMD5 = Md5keyUtil.newInstance().getKeyBeanOfStr(url);
  50. String path = realFile.getAbsolutePath() + "/" + urlMD5;
  51. try {
  52. File file = new File(path);
  53. if (file.exists()) {
  54. file.delete();
  55. }
  56. FileOutputStream fis = new FileOutputStream(file);
  57. BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fis));
  58. long currentTime = System.currentTimeMillis();
  59. bw.write(currentTime + "");
  60. bw.newLine();
  61. bw.write(json);
  62. bw.close();
  63. } catch (Exception e) {
  64. e.printStackTrace();
  65. }
  66. }
  67. /**
  68. * 根据缓存地址,从缓存中取出数据
  69. *
  70. * @param url
  71. * @return
  72. */
  73. public String getCacheToLocalJson(String url) {
  74. StringBuilder sb = new StringBuilder();
  75. String urlMD5 = Md5keyUtil.newInstance().getKeyBeanOfStr(url);
  76. // 创建缓存文件夹
  77. File file = new File(realFile, urlMD5);
  78. if (file.exists()) {
  79. try {
  80. FileReader fr = new FileReader(file);
  81. BufferedReader br = new BufferedReader(fr);
  82. br.readLine();
  83. String temp;
  84. while ((temp = br.readLine()) != null) {
  85. sb.append(temp);
  86. }
  87. } catch (Exception e) {
  88. e.printStackTrace();
  89. return null;
  90. }
  91. }
  92. return sb.toString();
  93. }
  94. }