如何保存和加载混合数据类型?

时间:2012-06-26 07:31:00

标签: android save

我需要在应用程序启动时保存和加载几十个数据。它们是int,String,long,数组数据类型。我很困惑,似乎有很多方法可以做到这一点。似乎每种变化都有不同的方法。应用程序运行时会修改部分数据。可以说我有以下

  int WifiOn="1";
  private long Lasttime="00/00/00";
  private String UserId="12345678";
  private String URLResource[]= {"A","B","C");
  //I open file...
  FileOutputStream fos = openFileOutput("userPref.dat", Context.MODE_PRIVATE);

接下来我将使用四种数据类型将其保存到内部存储中? 然后加载它们的方法是什么?

3 个答案:

答案 0 :(得分:1)

ID数据有限,可以使用shared preference,如果数据很多,可以使用SQLite database

 dozen pieces of data

最好使用SQLite数据库,这也是为您的需求而轻松高效的

请参阅link了解如何使用

根据http://developer.android.com/guide/topics/data/data-storage.html

您的数据存储选项如下:

  • 共享偏好设置

将私有原始数据存储在键值对中。

  • 内部存储

将私人数据存储在设备内存中。

  • 外部存储

将公共数据存储在共享外部存储上。

  • SQLite数据库

将结构化数据存储在私人数据库中。

  • 网络连接

使用您自己的网络服务器在网络上存储数据。

答案 1 :(得分:1)

如果所有数据的格式完全相同,则应该使用JSON,在函数中可以创建对象,然后将它们写入文件。

public bool writeToFile(int wifiOn, long lastTime, String userId, String [] urlResources) {
   JSONObject toStore = new JSONObject();
   FileOutputStream fos = openFileOutput("userPref.dat", Context.MODE_PRIVATE);

   toStore.put("wifiOn", wifiOn);
   toStore.put("lastTime", lastTime);
   toStore.put("userId", userId);
   toStore.put("urlResources", urlResources);

   try {
       fos.write(toStore.toString().getBytes());
       fos.close();
       return true;
   } catch (Exception e) {
       e.printStackTrace();
   }
   return false;
}

答案 2 :(得分:1)

除了Dheeresh Singh提及的SharedPreferenceSQLite databases之外,您还可以使用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中以挤出一些额外的读/写性能。