android---------SD卡操作类

本文介绍了一种在Android应用中管理SD卡图片并实现缓存优化的方法,包括图片保存、加载、SD卡与缓存之间的交互及过期文件处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.amaker.util;


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.StatFs;

/**
* Picture SD Util
*
* @author BlackTiger
* @version 1.0
*/
public class PictureSDUtil {
private Context mContext;
private static boolean ishasSD;
private Bitmap bitmap;
private Drawable defaultDrawable;
private HashMap<String, SoftReference<Drawable>> imageCache;
private final static String SD_PATH = Environment
.getExternalStorageDirectory() + "/meilijie/imgs/";
private final static String MYLIKE_SD_PATH = Environment
.getExternalStorageDirectory() + "/meilijie/mylike/";
private List<String> my_like_urls = new ArrayList<String>();
// 图片保存的时间暂定为3天
private long mTimeDiff = 864000000 * 3;

/**
* 构造方法
*
* @param mContext
*/
@SuppressWarnings("unused")
public PictureSDUtil(Context context) {
File file = new File(SD_PATH.toString());
File file2 = new File(MYLIKE_SD_PATH.toString());
this.mContext = context;
imageCache = new HashMap<String, SoftReference<Drawable>>();
defaultDrawable = mContext.getResources().getDrawable(R.drawable.icon);
}

/**
* 手机是否有内存卡的判断
*
* @return ishasSD
*/
public boolean getSdcard() {
ishasSD = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
return ishasSD;
}

/**
* 获取SD卡剩余空间大小
*
* @return freesdMB
*/
public static int freeSD() {
StatFs sf = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
double freesdMB = ((double) sf.getAvailableBlocks() * sf.getBlockSize())
/ (1024 * 1024);
return (int) freesdMB;
}

/**
* 判断图片是否存在于SD卡中
*
* @return boolean
*/
public boolean isExist(String path) {
String fileName = urlToFileName(path);
File imgFile = new File(SD_PATH + fileName);
if (imgFile.exists()) {
if (imgFile.isFile()) {
return true;
}
}
return false;
}

/**
* 保存文件
*
* @param bm
* @param fileName
* @throws IOException
*/
public Drawable saveFile(String path, Drawable drawable) {
URL url;
try {
url = new URL(
"http://tyy/login/hd_checknew.asp?v1=ch&v2=1&v3=LTRADER");
URLConnection con;
try {
con = url.openConnection();
con.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 5.0; Win32)");
con.connect();
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}

String fileName = urlToFileName(path);
File myCaptureFile = new File(SD_PATH.toString() + fileName);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
ByteArrayOutputStream oaos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 100, oaos);
InputStream is = new ByteArrayInputStream(oaos.toByteArray());

FileOutputStream fos = null;
byte[] b = new byte[1024];
int len = 0;
try {
fos = new FileOutputStream(myCaptureFile);
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();

File file = new File(SD_PATH.toString());
if (!file.exists()) {
file.mkdirs();
}

} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return new BitmapDrawable(bitmap);

}

/**
* 读取文件
*
* @param path
* @return Bitmap
*/
public Drawable loadImageFromUrl(String path) {
InputStream in = null;
Drawable drawable = null;
Bitmap bitmap = null;
// 第一;首先判断缓存中是否有这张图片,如果有,则取出
if (imageCache.containsKey(path)) {
SoftReference<Drawable> soft = imageCache.get(path);
drawable = soft.get();
if (drawable != null) {
return drawable;
}
} else {
// 第二;判断SD卡中是否有这张图片,如果没有,则下载,并放入缓存中。
if (!isExist(path)) {
try {
in = new URL(path).openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

if (in == null) {
return defaultDrawable;
} else {
try {
drawable = Drawable.createFromStream(in, "src");
if (drawable == null) {
return defaultDrawable;
} else {
imageCache.put(path, new SoftReference<Drawable>(
drawable));
if (getSdcard() && freeSD() > 20) {
// 保存图片到SD卡中
saveFile(path, drawable);
}
}
s
} catch (OutOfMemoryError out) {
return defaultDrawable;
} catch (Exception e) {
return defaultDrawable;
}
}
return drawable;
} else {
// 第三;如果SD卡中有这张图片,把这张图片放入缓存。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inTempStorage = new byte[5 * 1024]; // 16MB的临时存储空间
bitmap = BitmapFactory.decodeFile(SD_PATH.toString()
+ urlToFileName(path), options);
imageCache.put(path, new SoftReference<Drawable>(
new BitmapDrawable(bitmap)));
return new BitmapDrawable(bitmap);
}
}
return null;

}

// 只从SD卡中读取文件,暂不关心缓存(瀑布流)
public Drawable loadImageFromSD(String path) {
InputStream in = null;
Drawable drawable = null;
Bitmap bitmap = null;
if (!isExist(path)) {
try {
in = new URL(path).openStream();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

if (in == null) {
return defaultDrawable;
} else {
try {
drawable = Drawable.createFromStream(in, "src");
if (drawable == null) {
return defaultDrawable;
} else {
if (getSdcard() && freeSD() > 20) {
// 保存图片到SD卡中
saveFile(path, drawable);
}
}

} catch (OutOfMemoryError out) {
return defaultDrawable;
} catch (Exception e) {
return defaultDrawable;
}
}
return drawable;
} else {
// 第三;如果SD卡中有这张图片,把这张图片放入缓存。
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
options.inTempStorage = new byte[5 * 1024]; // 16MB的临时存储空间
bitmap = BitmapFactory.decodeFile(SD_PATH.toString()
+ urlToFileName(path), options);
return new BitmapDrawable(bitmap);
}
}

// 从SD卡中读取我喜欢的图片的url:
public List<String> getMyLikeFiles() {
// 得到图片文件夹下所有的图片名
File dd = new File(MYLIKE_SD_PATH);
String[] fs = dd.list();
my_like_urls = Arrays.asList(fs);
return my_like_urls;
}


/**
* 文件的复制(从一个文件夹复制到新的文件夹)
*
* @param sourceFile
* 源文件
* @param targetFile
* 目标文件
*/
// 复制文件
public static void copyFile(String filename) throws IOException {
// 新建文件输入流并对它进行缓冲
FileInputStream input = new FileInputStream(SD_PATH + filename);
BufferedInputStream inBuff = new BufferedInputStream(input);

// 新建文件输出流并对它进行缓冲
FileOutputStream output = new FileOutputStream(MYLIKE_SD_PATH
+ filename);
BufferedOutputStream outBuff = new BufferedOutputStream(output);

// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();

// 关闭流
inBuff.close();
outBuff.close();
output.close();
input.close();
}

/**
* 获取资源文件:
*
* @param context
* @param resId
*/
public static Bitmap readBitmap(Context context, int resId) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
// 获取资源图片
InputStream is = context.getResources().openRawResource(resId);
return BitmapFactory.decodeStream(is, null, opt);
}

/**
* 回收bitmap
*
* @param bmp
*/
public static void recycle(Bitmap bmp) {
if (bmp != null && !bmp.isRecycled()) {
bmp.recycle(); // 回收图片所占的内存
System.gc(); // 提醒系统及时回收
}
}

/**
* 截取url获取文件名
*
* @param imageUrl
* @return fileName
*/
public String urlToFileName(String path) {
String[] buffers = path.split("/");
int count = buffers.length;
String fileName = buffers[count - 1];
return fileName;
}

/**
* 修改文件的最后修改时间
*
* @param dir
* @param fileName
*/
public void updateFileTime(String dir, String fileName) {
File file = new File(dir, fileName);
long newModifiedTime = System.currentTimeMillis();
file.setLastModified(newModifiedTime);
}

/**
* 删除过期文件 24小时 = 86 400 000 毫秒
*
* @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();
}
}

/**
* Bitmap转Drawable
*
* @param bitmap
* @return bitmapDrawable
*/
public Drawable putBitmapToDrawable(Bitmap bitmap) {
BitmapDrawable bitmapDrawable = new BitmapDrawable(
mContext.getResources(), bitmap);
return bitmapDrawable;
}

/**
* Drawable转Bitmap
*
* @param drawable
* @return bitmap
*/
public Bitmap putDrawableToBitmap(Drawable drawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
return bitmap;
}

/**
* 获取图片的路径
*
* @param drawable
* @return bitmap
*/
public String getSdPicturePath() {
return SD_PATH;
}

public String getMyLikeSdPath() {
return MYLIKE_SD_PATH;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值