今天老板突然说,要给用户友评做个缓存,不至于一上来就请求数据库。
可是当断网的时候,缓存读取出现了中文乱码。不是一下子都是乱的,而是个别字是乱码。
后来网上看到用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;
}
网友评论