除了SharedPreference
s 和SQLite databases
Dheeresh Singh 提到的之外,您还可以使用Serialization
,因为您只使用简单的数据类型。
如何通过序列化将数据写入文件:
//create an ObjectOutputStream around your (file) OutputStream
ObjectOutputStream oos = new ObjectOutputStream(fos);
//The OOS has methods like writeFloat(), writeInt() etc.
oos.writeInt(myInt);
oos.writeInt(myOtherInt);
//You can also write objects that implements Serializable:
oos.writeObject(myIntArray);
//Finally close the stream:
oos.flush();
oos.close();
如何通过序列化从文件中读取数据:
//Create an ObjectInputStream around your (file) InputStream
ObjectInputStream ois = new ObjectInputStream(fis);
//This stream has read-methods corresponding to the write-methods in the OOS, the objects are read in the order they were written:
myInt = ois.readInt();
myOtherInt = ois.readInt();
//The readObject() returns an Object, but you know it is the same type that you wrote, so just cast it and ignore any warnings:
myIntArray = (int[]) ois.readObject();
//As always, close the stream:
ois.close();
附带说明一下,考虑将 In/OutStream 包装在 BufferedInput/OutputStream 中,以挤出一些额外的读/写性能。