特点:
int
、float
、String
、boolean
等) apply()
同步提交 适用场景:
示例代码:
// 获取SharedPreferences对象 SharedPreferences sp = getSharedPreferences("config", MODE_PRIVATE); // 写入数据 sp.edit() .putString("username", "admin") .putInt("age", 25) .apply(); // 提交修改 // 读取数据 String username = sp.getString("username", "default"); int age = sp.defaultAppConfig.getInt("age", 0);
优点:
缺点:
特点:
/data/data/包名/databases/
) 适用场景:
示例代码:
// 创建数据库帮助类 public class DBHelper extends SQLiteOpenHelper { public DBHelper(Context context) { super(context, "app.db", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE user (id INTEGER PRIMARY KEY, name TEXT)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {} } // 增删改查操作 DBHelper dbHelper = new DBHelper(context); SQLiteDatabase db = dbHelper.getWritableDatabase(); db.execSQL("INSERT INTO user (name) VALUES ('Alice')"); Cursor cursor = db.query("user", null, null, null, null, null, null);
优点:
缺点:
特点:
WRITE_EXTERNAL_STORAGE
适用场景:
示例代码:
// 写入内部存储文件 File file = new File(getFilesDir(), "data.txt"); try (FileOutputStream fos = new FileOutputStream(file)) { fos.write("Hello World".getBytes()); } // 读取内部存储文件 byte[] buffer = new byte[1024]; try (FileInputStream fis = new FileInputStream(file)) { int len = fis.read(buffer); String content = new String(buffer, 0, len); }
优点:
缺点:
特性 | SharedPreferences | SQLite | 文件存储 |
---|---|---|---|
数据类型 | 基本类型 | 结构化数据 | 任意格式文件 |
持久性 | 是 | 是 | 是 |
操作复杂度 | 低 | 中 | 低(文件IO) |
适用场景 | 轻量配置 | 复杂数据 | 大文件/多媒体 |
存储容量 | 小 | 中等 | 大 |
线程安全 | 是 | 否(需加锁) | 否 |
解答:
SharedPreferences
SQLite
File
的缓存目录 commit()
和apply()
有什么区别?解答:
commit()
:同步提交,返回boolean
表示成功/失败,会阻塞主线程。 apply()
:异步提交,无返回值,不会阻塞主线程,性能更优。apply()
,避免UI卡