我正在检索/下载JSON
feed作为InputStreamReader
,我需要将此InputStreamReader
转换为JsonReader
以解析它。如何以较少的开销在文本文件中保存并检索InputStream
JsonReader reader = new JsonReader(isr); // isr is the InputStreamReader instance
一切都好。但我想将这些数据以某种其他格式缓存到内部存储器中供以后使用。为了缓存,我使用文本文件进行保存。 (AFAIK,android默认缓存将数据保存在外部存储中,一些设备没有外部存储)。
为保存这个文件,我使用的是.txt
文件。但我只能将String
格式化的数据保存/缓存到文件中,并将其读取为String
。这是我至今写来写&读取文件中的代码:
public static void writeObject(Context context, String key, Object object)
throws IOException {
FileOutputStream fos = context
.openFileOutput(key, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(object);
oos.close();
fos.close();
}
public static Object readObject(Context context, String key)
throws IOException, ClassNotFoundException {
FileInputStream fis = context.openFileInput(key);
ObjectInputStream ois = new ObjectInputStream(fis);
Object object = ois.readObject();
return object;
}
但是,这种方法是服用过多的转换:
inputStreamReader -> inputStream -> String //to save
String -> inputStream -> inputStreamReader // retrieve
如何保存/缓存此数据以更少的开销?也许inputStreamReader
需要转换为outputStreamReader
或类似的东西是可写的。但我无法弄清楚这个联想代码。代码应该是什么?我也可以通过android的建议方式缓存这些数据,以备后用,将其保存为.txt
文件?