FileCache.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public interface FileCache {
public FileEntry get(String key);
public void put(String key, ByteProvider provider) throws IOException;
public void put(String key, InputStream is) throws IOException;
public void put(String key, File sourceFile, boolean move) throws IOException;
public void remove(String key);
public void clear();
public boolean has(String key);
}
FileEntry.java
public class FileEntry {
private String key;
private File file;
public FileEntry(String key, File file) {
this.key = key;
this.file = file;
}
public InputStream getInputStream() throws IOException {
return new BufferedInputStream(new FileInputStream(file));
}
public String getKey() {
return key;
}
public File getFile() {
return file;
}
}
FileCacheImpl.java
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class FileCacheImpl implements FileCache {
private CacheStorage cacheStorage;
public FileCacheImpl(File cacheDir, int maxKBSizes) {
long maxBytesSize = maxKBSizes <= 0 ? 0 : maxKBSizes * 1024;
cacheStorage = new CacheStorage(cacheDir, maxBytesSize);
}
@Override
public FileEntry get(String key) {
File file = cacheStorage.get(keyToFilename(key));
if (file == null) {
return null;
}
if (file.exists()) {
return new FileEntry(key, file);
}
return null;
}
@Override
public void put(String key, ByteProvider provider) throws IOException {
cacheStorage.write(keyToFilename(key), provider);
}
@Override
public void put(String key, InputStream is) throws IOException {
put(key, ByteProviderUtil.create(is));
}
@Override
public void put(String key, File sourceFile, boolean move)
throws IOException {
if (move) {
cacheStorage.move(keyToFilename(key), sourceFile);
} else {
put(key, ByteProviderUtil.create(sourceFile));
}
}
@Override
public void remove(String key) {
cacheStorage.delete(keyToFilename(key));
}
private String keyToFilename(String key) {
String filename = key.replace(":", "_");
filename = filename.replace("/", "_s_");
filename = filename.replace("\\", "_bs_");
filename = filename.replace("&", "_bs_");
filename = filename.replace("*", "_start_");
filename = filename.replace("?", "_q_");
filename = filename.replace("|", "_or_");
filename = filename.replace(">", "_gt_");
filename = filename.replace("<", "_lt_");
return filename;
}
@Override
public void clear() {
cacheStorage.deleteAll();
}
@Override
public boolean has(String key) {
return cacheStorage.has(key);
}
}
IOUtils.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public abstract class IOUtils {
public static String read(InputStream is) throws IOException {
InputStreamReader reader = null;
try {
reader = new InputStreamReader(is);
StringBuilder builder = new StringBuilder();
char[] readDate = new char[1024];
int len = -1;
while ((len = reader.read(readDate)) != -1) {
builder.append(readDate, 0, len);
}
return builder.toString();
} finally {
close(reader);
}
}
public static void copy(InputStream is, OutputStream out)
throws IOException {
byte[] buff = new byte[4096];
int len = -1;
while ((len = is.read(buff)) != -1) {
out.write(buff, 0, len);
}
}
public static void copy(File source, OutputStream os) throws IOException {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(source));
IOUtils.copy(is, os);
} finally {
IOUtils.close(is);
}
}
public static void copy(InputStream is, File target) throws IOException {
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(target));
IOUtils.copy(is, os);
} finally {
IOUtils.close(os);
}
}
public static void copy(String str, OutputStream os) throws IOException {
os.write(str.getBytes());
}
public static void close(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
}
}
}
}
FileCacheFactory.java
import android.content.Context;
import java.io.File;
import java.util.HashMap;
public class FileCacheFactory {
private static boolean initialized = false;
private static FileCacheFactory instance = new FileCacheFactory();
public static void initialize(Context context, String file_dir) {
if (!initialized) {
synchronized (instance) {
if (!initialized) {
instance.init(context,file_dir);
initialized = true;
}
}
}
}
public static FileCacheFactory getInstance() {
if (!initialized) {
throw new IllegalStateException(
"Not initialized. You must call FileCacheFactory.initialize() before getInstance()");
}
return instance;
}
private HashMap<String, FileCache> mCacheMap = new HashMap<String, FileCache>();
private File mCacheBaseDir;
private FileCacheFactory() {
}
private void init(Context context) {
mCacheBaseDir = context.getCacheDir();
}
private void init(Context context, String file_dir) {
// cacheBaseDir = context.getCacheDir();
mCacheBaseDir = new File(file_dir);
}
public FileCache create(String cacheName, int maxKbSizes) {
synchronized (mCacheMap) {
FileCache cache = mCacheMap.get(cacheName);
File cacheDir = new File(mCacheBaseDir, cacheName);
if (cache != null) {
try {
cache = new FileCacheImpl(cacheDir, maxKbSizes);
mCacheMap.put(cacheName, cache);
} catch (Exception e) {
String.format("FileCache[%s] Aleady exists", cacheName);
}
}
return cache;
}
}
public FileCache get(String cacheName) {
synchronized (mCacheMap) {
FileCache cache = mCacheMap.get(cacheName);
if (cache == null) {
try {
}catch (Exception e)
{
String.format("FileCache[%s] not founds.", cacheName);
}
}
return cache;
}
}
public void destroy(String cacheName)
{
FileCache cache = mCacheMap.get(cacheName);
File file = new File(mCacheBaseDir+File.separator+cacheName);
if(file.exists())
{
file.delete();
}
}
public void clear(){
mCacheMap.clear();
}
public boolean has(String cacheName) {
return mCacheMap.containsKey(cacheName);
}
}
설명
캐시 디렉토리 안에 캐시파일이 여러개 저장되는 방식입니다.
사용방법
1. 캐시 디렉토리
private FileCache mFileCache = null;
public static final String CACHE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "FolderName" + File.separator + ".cache"; //캐시 기본폴더
FileCacheFactory.initialize(mContext, CACHE_PATH);
if (!FileCacheFactory.getInstance().has(zipDirName)) // 해당 키의 캐시 디렉토리가 있는지 확인
{
FileCacheFactory.getInstance().create(zipDirName, 0); // 캐시디렉토리가 없을경우 만든다.
}
mFileCache = FileCacheFactory.getInstance().get(zipDirName); // 해당 파일의 캐시 디렉토리를 가져온다.
- 캐시 객체 생성
FileCacheFactory.initialize(mContext, CACHE_PATH);
- 캐시디렉토리 존재 여부 체크
FileCacheFactory.getInstance().has(Dirkey)
- 캐시디렉토리 생성
FileCacheFactory.getInstance().create(Dirkey, 0); // 캐시디렉토리가 없을경우 만든다.
- 캐시디렉토리 가져오기
mFileCache = FileCacheFactory.getInstance().get(Dirkey); // 해당 파일의 캐시 디렉토리를 가져온다.
2. 캐시
-캐시 저장
/**
* @param key cache 키
* @param val cache 내용
* @param isMove ture = val파일이 캐시경로로 이동됨, false = val파일이 캐시경로로 복사됨
*/
private void setCacheFile(String key, File val, boolean isMove) {
if (!mFileCache.has(key)) {
try {
mFileCache.put(key, val, isMove);
} catch (IOException e) {
e.printStackTrace();
}
}
}
-캐시 가져오기
/**
* 캐시내용을 가져온다.
* @param key cache 키
* @return
*/
public FileEntry getCacheFile(String key) {
return mFileCache.get(key);
}
728x90
반응형
'Android' 카테고리의 다른 글
EditText 숫자,영어,한글 문자입력제한 (0) | 2017.06.13 |
---|---|
안드로이드 파일 이름및 확장자 가져오기 (0) | 2017.05.23 |
안드로이드 File 복사 (2) | 2017.05.23 |
안드로이드 O priview 폰트 혹은 글꼴 (0) | 2017.04.25 |
안드로이드 ProgressDialog 만들기 (0) | 2017.03.09 |