Skip to content

Instantly share code, notes, and snippets.

@m7mdra
Created March 28, 2017 08:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m7mdra/fe7fcd2c35c89257001ed085ec592207 to your computer and use it in GitHub Desktop.
Save m7mdra/fe7fcd2c35c89257001ed085ec592207 to your computer and use it in GitHub Desktop.
LruCache
package util;
import com.jakewharton.disklrucache.DiskLruCache;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Cache {
private DiskLruCache mDiskLruCache;
public Cache(File directory) throws IOException {
mDiskLruCache = DiskLruCache.open(directory, 1, 1, 20 * 2^20);
}
public void put(String key, Object object) {
DiskLruCache.Editor editor;
try {
editor = mDiskLruCache.edit(key);
if (editor == null) {
return;
}
ObjectOutputStream out = new ObjectOutputStream(editor.newOutputStream(0));
out.writeObject(object);
out.close();
editor.commit();
} catch (IOException e) {
e.printStackTrace();
}
}
public Object get(String key) {
DiskLruCache.Snapshot snapshot;
try {
snapshot = mDiskLruCache.get(key);
if (snapshot==null)
return "";
ObjectInputStream in = new ObjectInputStream(snapshot.getInputStream(0));
return in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public String isNullOrEmpty(String key){
return this.get(key).toString().isEmpty()?"null":"not null";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment