CacheUtils.java 2.7 KB

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