安卓系统提供了多种本地存储方案,开发者可根据数据类型、存储需求、性能要求等选择合适方式,以下是常见的存储对象到本地的实现方案:
适用场景:轻量级配置信息、简单数据(如用户设置、登录状态)
特点:基于XML文件,支持putString()
、putInt()
等基础数据类型,需手动序列化对象。
存储对象步骤:
edit().putString().apply()
保存// 示例:存储User对象 SharedPreferences sp = getSharedPreferences("app_config", MODE_PRIVATE); User user = new User("Alice", 25); String json = new Gson().toJson(user); // 需添加Gson依赖 sp.edit().putString("user_data", json).apply();
读取对象步骤:
getString()
获取JSON字符串String json = sp.getString("user_data", ""); User user = new Gson().fromJson(json, User.class);
适用场景:大文本文件、二进制文件(如图片、视频)、复杂对象持久化
特点:需处理文件路径、序列化逻辑,支持InternalStorage
(私有)和ExternalStorage
(公有)。
存储对象步骤:
FileOutputStream
写入文件// 示例:存储对象为JSON文件 User user = new User("Bob", 30); File file = new File(getFilesDir(), "user.json"); try (FileOutputStream fos = new FileOutputStream(file)) { String json = new Gson().toJson(user); fos.write(json.getBytes()); }
读取对象步骤:
FileInputStream
读取文件内容File file = new File(getFilesDir(), "user.json"); try (FileInputStream fis = new FileInputStream(file)) { byte[] bytes = new byte[(int) fis.available()]; fis.read(bytes); String json = new String(bytes); User user = new Gson().fromJson(json, User.class); }
适用场景:复杂数据关系、频繁查询、事务操作
特点:需手动创建表结构,适合存储多个对象实例。
存储对象步骤:
users
表)// 示例:插入User对象到SQLite SQLiteDatabase db = SQLiteOpenHelper.getInstance().getWritableDatabase(); ContentValues values = new ContentValues(); values.put("name", user.getName()); values.put("age", user.getAge()); db.insert("users", null, values);
读取对象步骤:
SELECT
查询Cursor cursor = db.query("users", null, "id=?", new String[]{"1"}); if (cursor.moveToFirst()) { User user = new User( cursor.getString(cursor.getColumnIndex("name")), cursor.getInt(cursor.getColumnIndex("age")) ); }
适用场景:替代SharedPreferences,支持类型安全、异步操作
特点:基于Kotlin协程,需配置PreferenceDataStore
或ProtoDataStore
。
存储对象示例:
// 使用ProtoDataStore存储对象 val dataStore = DataStoreFactory.createProtoDataStore(context) val userProto = UserProto.User.newBuilder() .setName("Charlie") .setAge(28) .build() dataStore.edit { settings -> settings[KEY_USER] = userProto.toByteArray() }
存储方式 | 数据格式 | 适用场景 | 是否需要序列化 | 支持查询 |
---|---|---|---|---|
SharedPreferences | Key-Value(原始类型) | 简单配置、轻量级数据 | 是(对象需转JSON) | 否 |
文件存储 | 文本/二进制 | 大文件、复杂对象 | 是 | 否 |
SQLite | 关系型表结构 | 多对象关联、复杂查询 | 否(直接存字段) | 是 |
DataStore | 协议缓冲/键值对 | 现代安卓应用配置(替代SP) | 是(Proto/JSON) | 否 |
解答:
DataStore
或SharedPreferences
。 SQLite
或文件存储(如序列化JSON)。 DataStore
支持异步操作,性能更优。解答:
TypeConverter
(配合Room)。 .proto
文件描述嵌套结构,通过协议缓冲