java缓存图片路径_java实现图片文件的缓存工具实现解析

阿里 阅读:286 2021-04-01 12:34:10 评论:0

package com.demo.loading;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.util.Arrays;

import java.util.Comparator;

import org.apache.commons.lang.StringUtils;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.os.Environment;

import android.os.StatFs;

public class ImageFileCache {

private static final String WHOLESALE_CONV = ".cach";

/** 过期时间3天 **/

private static final long mTimeDiff = 3 * 24 * 60 * 60 * 1000;

private String cardType = null;

public ImageFileCache() {

// 清理文件缓存

removeCache(getDirectory());

}

/**

* 通过URL获取图片

*

* @param url

* @return Bitmap

*/

public Bitmap getImage(final String url) {

final String path = getDirectory() + "/" + convertUrlToFileName(url);

File file = new File(path);

if (file.exists()) {

Bitmap bmp = BitmapFactory.decodeFile(path);

if (bmp == null) {

file.delete();

} else {

updateFileTime(path);

return bmp;

}

}

return null;

}

/**

* 判断图片是否存在

*

* @param url

*/

public Boolean exists(String url) {

String path = getDirectory() + "/" + convertUrlToFileName(url);

File file = new File(path);

return file.exists();

}

/**

* 刪除缓存文件

*

* @param url

*/

public void deleteFile(String url) {

try {

if (StringUtils.isNotBlank(url)) {

final String path = getDirectory() + "/"

+ convertUrlToFileName(url);

File file = new File(path);

if (file != null && file.exists()) {

file.delete();

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

/*** 缓存空间大小 ****/

private static final int FREE_SD_SPACE_NEEDED_TO_CACHE = 10;

/**

* 保存图片到SD卡

*

* @param bm

* @param url

*/

public void saveBmpToSd(Bitmap bm, String url) {

if (bm == null) {

// 需要保存的是一个空值

return;

}

// 判断sdcard上的空间

if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {

// SD空间不足

return;

}

String filename = convertUrlToFileName(url);

String dir = getDirectory();

File fileDir = new File(dir);

if (!fileDir.exists()) {

fileDir.mkdirs();

}

File file = new File(dir + "/" + filename);

try {

file.createNewFile();

OutputStream outStream = new FileOutputStream(file);

bm.compress(Bitmap.CompressFormat.PNG, 10, outStream);

outStream.flush();

outStream.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 保存图片到SD卡

*

* @param bData

* @param url

*/

public void saveBmpToSd(byte[] bData, String url, String cardType) {

this.cardType = cardType;

if (bData == null) {

// 需要保存的是一个空值

return;

}

// 判断sdcard上的空间

if (FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {

// SD空间不足

return;

}

String filename = convertUrlToFileName(url);

String dir = getDirectory();

File fileDir = new File(dir);

if (!fileDir.exists()) {

fileDir.mkdirs();

}

File file = new File(dir + "/" + filename);

FileOutputStream fos = null;

try {

file.createNewFile();

fos = new FileOutputStream(file);

fos.write(bData);

} catch (Exception e) {

file.delete();

e.printStackTrace();

} finally {

try {

fos.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

private static final int CACHE_SIZE = 10;

/**

* 清理缓存 计算存储目录下的文件大小,

* 当文件总大小大于规定的CACHE_SIZE或者sdcard剩余空间小于FREE_SD_SPACE_NEEDED_TO_CACHE的规定

* 那么删除40%最近没有被使用的文件

*

* @param dirPath

*/

private boolean removeCache(String dirPath) {

File dir = new File(dirPath);

File[] files = dir.listFiles();

if (files == null) {

return true;

}

if (!android.os.Environment.getExternalStorageState().equals(

android.os.Environment.MEDIA_MOUNTED)) {

return false;

}

int dirSize = 0;

for (int i = 0; i < files.length; i++) {

if (files[i].getName().contains(WHOLESALE_CONV)) {

dirSize += files[i].length();

}

}

if (dirSize > CACHE_SIZE * MB

|| FREE_SD_SPACE_NEEDED_TO_CACHE > freeSpaceOnSd()) {

int removeFactor = (int) ((0.4 * files.length) + 1);

Arrays.sort(files, new FileLastModifSort());

for (int i = 0; i < removeFactor; i++) {

if (files[i].getName().contains(WHOLESALE_CONV)) {

files[i].delete();

}

}

}

if (freeSpaceOnSd() <= CACHE_SIZE) {

return false;

}

return true;

}

/**

* 根据文件的最后修改时间进行排序*

*/

private class FileLastModifSort implements Comparator {

public int compare(File arg0, File arg1) {

if (arg0.lastModified() > arg1.lastModified()) {

return 1;

} else if (arg0.lastModified() == arg1.lastModified()) {

return 0;

} else {

return -1;

}

}

}

/**

* 删除过期文件

*

* @param dirPath

* @param filename

*/

public void removeExpiredCache(String dirPath, String filename) {

File file = new File(dirPath, filename);

if (System.currentTimeMillis() - file.lastModified() > mTimeDiff) {

file.delete();

}

}

/**

* 修改文件的最后修改时间 这里需要考虑,是否将使用的图片日期改为当前日期

*

* @param path

*/

public void updateFileTime(String path) {

File file = new File(path);

long newModifiedTime = System.currentTimeMillis();

file.setLastModified(newModifiedTime);

}

/**

* 计算sdcard上的剩余空间

*

* @return

*/

private int MB = 1024 * 1024;

/**

* 计算sdcard上的剩余空间

*

* @return

*/

private int freeSpaceOnSd() {

StatFs stat = new StatFs(Environment.getExternalStorageDirectory()

.getPath());

double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat

.getBlockSize()) / MB;

return (int) sdFreeMB;

}

/** 将url转成文件名 **/

private String convertUrlToFileName(String url) {

// String[] strs = url.split("/");

String fileName = "";

if (url.contains(".jpg"))

fileName = cardType + ".jpg";// + WHOLESALE_CONV;

else if (url.contains(".png"))

fileName = cardType + ".png";

return fileName.replaceAll("[?]", "_");

}

/** 获得缓存目录 **/

private String getDirectory() {

String dir = getSDPath() + "/" + ConstantUtils.IMAGECACHDIR;

String substr = dir.substring(0, 4);

if (substr.equals("/mnt")) {

dir = dir.replace("/mnt", "");

}

return dir;

}

/**** 取SD卡路径不带/ ****/

public String getSDPath() {

File sdDir = null;

boolean sdCardExist = Environment.getExternalStorageState().equals(

android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在

if (sdCardExist) {

sdDir = Environment.getExternalStorageDirectory();// 获取跟目录

}

if (sdDir != null) {

return sdDir.toString();

} else {

return "";

}

}

/**

* http://www.cnblogs.com/TerryBlog/archive/2012/01/08/2316482.html

*/

}

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

关注我们