If you think the Android project sony-camera-remote-java listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
Java Source Code
package com.praetoriandroid.cameraremote.tool;
//fromwww.java2s.comimport com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
publicclass Cache {
private Map<String, String> data = new HashMap<String, String>();
private Gson gson = new Gson();
private String pathName;
private String fileName;
public Cache(String pathName, String fileName) throws IOException {
this.fileName = fileName;
this.pathName = pathName;
restore();
}
publicsynchronized String get(String key) {
synchronized (Cache.class) {
return data.get(key);
}
}
publicsynchronizedvoid put(String key, String value) throws IOException {
synchronized (Cache.class) {
data.put(key, value);
save();
}
}
privatevoid restore() throws IOException {
File path = newFile(pathName);
if (!path.exists()) {
return;
}
if (!path.isDirectory()) {
thrownew IOException(pathName + " is not a directory.");
}
File file = newFile(path, fileName);
if (!file.exists()) {
return;
}
FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte[] buffer = newbyte[1024];
int length = inputStream.read(buffer);
String configText = new String(buffer, 0, length, "UTF-8");
data = gson.fromJson(configText, new TypeToken<Map<String, String>>() {}.getType());
} finally {
if (inputStream != null) {
inputStream.close();
}
}
}
privatevoid save() throws IOException {
File path = newFile(pathName);
if (!path.exists()) {
if (!path.mkdirs()) {
thrownew IOException("Could not create directory " + pathName);
}
}
if (!path.isDirectory()) {
thrownew IOException(pathName + " is not a directory.");
}
File file = newFile(path, fileName);
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
outputStream.write(gson.toJson(data).getBytes());
} finally {
if (outputStream != null) {
outputStream.close();
}
}
}
}