FileUtil.java 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package com.benyanyi.okhttp.deprecated;
  2. import android.graphics.Bitmap;
  3. import android.os.Environment;
  4. import android.support.annotation.NonNull;
  5. import com.benyanyi.okhttp.util.FormatUtil;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. /**
  10. * @author myLove
  11. */
  12. class FileUtil {
  13. /**
  14. * @param saveDir
  15. * @return
  16. * @throws IOException 判断下载目录是否存在
  17. */
  18. static String isExistDir(String saveDir) throws IOException {
  19. // 下载位置
  20. File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
  21. if (!downloadFile.mkdirs()) {
  22. downloadFile.createNewFile();
  23. }
  24. String savePath = downloadFile.getAbsolutePath();
  25. return savePath;
  26. }
  27. /**
  28. * 图片保存
  29. */
  30. static String saveImage(Bitmap bitmap, String path) {
  31. File file = new File(path);
  32. try {
  33. if (!file.exists()) {
  34. file.createNewFile();
  35. }
  36. FileOutputStream fos = new FileOutputStream(file);
  37. String substring = path.substring(path.length() - 3, path.length());
  38. if ("png".equals(substring)) {
  39. bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
  40. } else {
  41. bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
  42. }
  43. fos.flush();
  44. fos.close();
  45. } catch (Exception e) {
  46. e.fillInStackTrace();
  47. }
  48. return path;
  49. }
  50. static String getSDPath() {
  51. File sdDir = null;
  52. boolean sdCardExist = Environment.getExternalStorageState()
  53. //判断sd卡是否存在
  54. .equals(Environment.MEDIA_MOUNTED);
  55. //判断sd卡是否存在
  56. if (sdCardExist) {
  57. //获取跟目录
  58. sdDir = Environment.getExternalStorageDirectory();
  59. }
  60. return sdDir.toString();
  61. }
  62. /**
  63. * @param url
  64. * @return 从下载连接中解析出文件名
  65. */
  66. @NonNull
  67. static String getNameFromUrl(String url) {
  68. return url.substring(url.lastIndexOf("/") + 1);
  69. }
  70. /**
  71. * 判断当前url下载的文件是否为自己所需的
  72. *
  73. * @param url
  74. * @param condition 判断条件
  75. * @return
  76. */
  77. static boolean ifUrl(String url, String condition) {
  78. String str = url.substring(url.lastIndexOf("."));
  79. if (FormatUtil.isNotEmpty(str)) {
  80. return str.equals(condition);
  81. } else {
  82. return false;
  83. }
  84. }
  85. }