简介:本文详细解析Android平台下多数据库存储的实现方法,涵盖SQLite多库管理、文件系统辅助存储及混合存储架构设计,提供可落地的技术方案。
Android系统提供五种核心数据存储方式:SharedPreferences(键值对存储)、SQLite数据库(关系型存储)、内部存储(应用私有文件)、外部存储(共享文件)和ContentProvider(跨应用共享)。在实际开发中,单一存储方式难以满足复杂业务需求,例如电商类应用需要同时管理用户信息(结构化数据)、商品图片(非结构化数据)和日志文件(流式数据)。
典型场景包括:
| 存储方式 | 读取速度 | 写入速度 | 并发能力 | 数据量级 |
|---|---|---|---|---|
| SQLite | 中 | 中 | 高 | GB级 |
| 文件存储 | 快 | 快 | 低 | TB级 |
| 内存存储 | 极快 | 极快 | 中 | MB级 |
Android通过SQLiteOpenHelper管理数据库,可通过包名+数据库名实现多库隔离:
public class MultiDBHelper extends SQLiteOpenHelper {private static final String DB_NAME = "user_db";private static final int VERSION = 1;public MultiDBHelper(Context context) {super(context, DB_NAME, null, VERSION);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");}}// 使用示例MultiDBHelper userHelper = new MultiDBHelper(context);SQLiteDatabase userDB = userHelper.getWritableDatabase();
实现数据库路由层,根据业务类型选择对应数据库:
public class DBRouter {private Map<String, SQLiteDatabase> dbMap = new HashMap<>();public SQLiteDatabase getDB(Context context, String dbName) {if (!dbMap.containsKey(dbName)) {SQLiteOpenHelper helper = new SQLiteOpenHelper(context, dbName, null, 1) {@Override public void onCreate(SQLiteDatabase db) {}@Override public void onUpgrade(SQLiteDatabase db, int old, int new) {}};dbMap.put(dbName, helper.getWritableDatabase());}return dbMap.get(dbName);}}
通过SQLiteDatabase.beginTransaction()实现多库事务:
try {db1.beginTransaction();db2.beginTransaction();// 执行多个数据库操作db1.insert("table1", null, contentValues1);db2.update("table2", contentValues2, "id=?", new String[]{"1"});db1.setTransactionSuccessful();db2.setTransactionSuccessful();} finally {db1.endTransaction();db2.endTransaction();}
Android提供三种存储类型:
// 应用私有目录(无需权限)File internalFile = context.getFilesDir(); // /data/data/<package>/filesFile cacheDir = context.getCacheDir(); // /data/data/<package>/cache// 外部存储(需要权限)File externalFile = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);File externalCache = context.getExternalCacheDir();
采用JSON/XML格式存储半结构化数据:
// 写入JSON文件JSONObject userData = new JSONObject();userData.put("name", "John");userData.put("age", 30);try (FileOutputStream fos = context.openFileOutput("user.json", Context.MODE_PRIVATE);OutputStreamWriter osw = new OutputStreamWriter(fos);BufferedWriter writer = new BufferedWriter(osw)) {writer.write(userData.toString());}// 读取JSON文件try (FileInputStream fis = context.openFileInput("user.json");InputStreamReader isr = new InputStreamReader(fis);BufferedReader reader = new BufferedReader(isr)) {StringBuilder sb = new StringBuilder();String line;while ((line = reader.readLine()) != null) {sb.append(line);}JSONObject data = new JSONObject(sb.toString());}
对于超过100MB的文件,采用分块存储策略:
public class ChunkedStorage {private static final int CHUNK_SIZE = 1024 * 1024; // 1MBpublic void writeChunk(File destFile, byte[] data, int chunkIndex) throws IOException {try (RandomAccessFile raf = new RandomAccessFile(destFile, "rw")) {raf.seek(chunkIndex * CHUNK_SIZE);raf.write(data);}}public byte[] readChunk(File srcFile, int chunkIndex) throws IOException {byte[] buffer = new byte[CHUNK_SIZE];try (RandomAccessFile raf = new RandomAccessFile(srcFile, "r")) {raf.seek(chunkIndex * CHUNK_SIZE);int bytesRead = raf.read(buffer);return Arrays.copyOf(buffer, bytesRead);}}}
| 层级 | 存储方式 | 访问频率 | 数据量 |
|---|---|---|---|
| 热数据 | SQLite内存数据库 | 高 | <10MB |
| 温数据 | SQLite磁盘数据库 | 中 | 10MB-1GB |
| 冷数据 | 文件存储 | 低 | >1GB |
实现LRU缓存+文件备份机制:
public class HybridStorage {private LruCache<String, byte[]> memoryCache;private File cacheDir;public HybridStorage(Context context, int maxSize) {memoryCache = new LruCache<>(maxSize);cacheDir = context.getCacheDir();}public byte[] getData(String key) {// 1. 检查内存缓存byte[] data = memoryCache.get(key);if (data != null) return data;// 2. 检查文件缓存File file = new File(cacheDir, key);if (file.exists()) {try (FileInputStream fis = new FileInputStream(file)) {data = fis.readAllBytes();memoryCache.put(key, data);return data;}}return null;}public void putData(String key, byte[] data) {// 1. 写入内存缓存memoryCache.put(key, data);// 2. 异步写入文件new AsyncTask<Void, Void, Void>() {@Override protected Void doInBackground(Void... voids) {try (FileOutputStream fos = new FileOutputStream(new File(cacheDir, key))) {fos.write(data);} catch (IOException e) {e.printStackTrace();}return null;}}.execute();}}
-- 复合索引示例CREATE INDEX idx_user_name_age ON users(name, age);-- 覆盖索引查询SELECT id, name FROM users WHERE age > 20;
BufferedInputStream/BufferedOutputStream减少系统调用
public class StorageMonitor {public static long getAvailableInternalStorage(Context context) {StatFs stat = new StatFs(context.getFilesDir().getPath());long blockSize = stat.getBlockSizeLong();long availableBlocks = stat.getAvailableBlocksLong();return availableBlocks * blockSize;}public static double getDatabaseSize(Context context, String dbName) {File dbFile = context.getDatabasePath(dbName);return dbFile.length() / (1024.0 * 1024.0); // MB}}
使用SQLCipher实现加密数据库:
// 依赖implementation 'net.zetetic:android-database-sqlcipher:4.4.3@aar'SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(databaseFile,"encryption_key",null,new SQLCipherOpenHelper.DatabaseErrorHandler() {@Override public void onCorruption(SQLiteDatabase dbObj) {}});
采用AES加密敏感文件:
public class FileEncryptor {private static final String ALGORITHM = "AES";private static final int KEY_SIZE = 256;public void encryptFile(File inputFile, File outputFile, SecretKey secretKey)throws Exception {Cipher cipher = Cipher.getInstance(ALGORITHM);cipher.init(Cipher.ENCRYPT_MODE, secretKey);try (FileInputStream fis = new FileInputStream(inputFile);FileOutputStream fos = new FileOutputStream(outputFile);CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {byte[] buffer = new byte[8192];int bytesRead;while ((bytesRead = fis.read(buffer)) != -1) {cos.write(buffer, 0, bytesRead);}}}}
典型应用架构示例:
[业务层]↓[数据访问层] → [内存缓存] → [数据库路由] → [SQLite集群]↓ ↓[文件存储] ← [加密模块] ← [安全模块]
通过合理组合SQLite多数据库管理和文件系统存储,可以构建出满足不同业务场景需求的高性能存储方案。实际开发中应根据数据特征、访问模式和安全要求进行针对性优化。