今天老板突然說,要給用戶友評做個緩存浮创,不至于一上來就請求數(shù)據(jù)庫忧吟。
可是當斷網(wǎng)的時候,緩存讀取出現(xiàn)了中文亂碼斩披。不是一下子都是亂的溜族,而是個別字是亂碼。
后來網(wǎng)上看到用BufferedReader這個類可以不亂碼垦沉,我就試了試煌抒。沒想到還真不錯,成功了厕倍!
public String getAsStringNew( String key )
{
BufferedReader buf = null;
StringBuffer stringBuffer = new StringBuffer();
try {
String line = null;
buf = new BufferedReader( new InputStreamReader( get( key ) ) );
while ( (line = buf.readLine() ) != null )
{
stringBuffer.append( line );
}
} catch ( IOException e ) {
e.printStackTrace();
} finally {
try {
buf.close();
} catch ( IOException e ) {
e.printStackTrace();
}
}
return(stringBuffer.toString() );
}
還有一個方法就是使用解碼寡壮。在緩存的時候轉碼,讀取緩存的時候解碼讹弯。
緩存時:
public void put(String key, String value) {
try {
value = URLEncoder.encode(value, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
DiskLruCache.Editor edit = null;
BufferedWriter bw = null;
try {
edit = editor(key);
if (edit == null) return;
OutputStream os = edit.newOutputStream(0);
bw = new BufferedWriter(new OutputStreamWriter(os));
bw.write(value);
edit.commit();//write CLEAN
} catch (IOException e) {
e.printStackTrace();
try {
//s
edit.abort();//write REMOVE
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
try {
if (bw != null)
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
讀取緩存時:
public String getAsString(String key) {
InputStream inputStream = null;
try {
//write READ
inputStream = get(key);
if (inputStream == null) return null;
StringBuilder sb = new StringBuilder();
int len = 0;
byte[] buf = new byte[128];
while ((len = inputStream.read(buf)) != -1) {
sb.append(new String(buf, 0, len));
}
return URLDecoder.decode(sb.toString(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
if (inputStream != null)
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return null;
}