Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

打造 Android 超輕量級本地數據存儲類

編輯:關於 Android 程式設計

用過 SharedPreferences 的人大概都對它又愛又恨——想存點小資料還得 commit,寫法總讓人覺得有點累贅。本篇就來做一個更輕巧的替代方案:一個基於 Properties 文件的鍵值對存儲類,介面簡潔,還能自訂存檔路徑。

LocalStorage.java:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import android.content.Context;

/**
 * Android 本地存儲,主要用於儲存簡單的 key-value 鍵值對。
 * 提供增、刪、改、查方法,可自訂路徑。
 */
public class LocalStorage {
    private static Properties properties = new Properties();
    private static String filepath;

    private LocalStorage() { }

    /** 以 Context + 檔名取得物件 */
    public static LocalStorage get(Context ctx, String fileName) {
        return get(ctx.getCacheDir() + "/" + fileName);
    }

    /** 以檔案絕對路徑取得物件 */
    public static LocalStorage get(String filePath) {
        createFile(filePath);
        filepath = filePath;
        try {
            properties.load(new FileInputStream(filepath));
            return new LocalStorage();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void createFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            String path = file.getAbsolutePath();
            String[] sourceStrArray = path.split("/");
            String dirPath = "";
            for (int i = 0; i < sourceStrArray.length - 1; i++) {
                if (!sourceStrArray[i].equals("")) {
                    dirPath += "/" + sourceStrArray[i];
                }
            }
            new File(dirPath).mkdirs();
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getAsString(String key) {
        if (key == null) return null;
        Properties props = new Properties();
        try {
            props.load(new FileInputStream(filepath));
            String value = props.getProperty(key);
            value = URLDecoder.decode(value, "utf-8");
            return value;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public int getAsInt(String key) {
        String str = getAsString(key);
        if (str == null) return -9999;
        return Integer.valueOf(str).intValue();
    }

    public boolean getAsBoolean(String key) {
        String str = getAsString(key);
        if (str == null) return false;
        return str.equals("true");
    }

    public long getAsLong(String key) {
        String str = getAsString(key);
        if (str == null) return -9999;
        return Long.valueOf(str).longValue();
    }

    public float getAsFloat(String key) {
        String str = getAsString(key);
        if (str == null) return -9999;
        return Float.valueOf(str).floatValue();
    }

    public double getAsDouble(String key) {
        String str = getAsString(key);
        if (str == null) return -9999;
        return Double.valueOf(str).doubleValue();
    }

    /** 新增 */
    public void put(String keyname, Object keyvalue) {
        String value = keyvalue.toString();
        try {
            value = URLEncoder.encode(value, "utf-8"); // 處理中文亂碼
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        try {
            OutputStream fos = new FileOutputStream(filepath);
            properties.setProperty(keyname, value);
            properties.store(fos, null);
        } catch (IOException e) { }
    }

    /** 更新 */
    public void update(String keyname, String keyvalue) {
        try {
            properties.load(new FileInputStream(filepath));
            OutputStream fos = new FileOutputStream(filepath);
            properties.setProperty(keyname, keyvalue);
            properties.store(fos, null);
        } catch (IOException e) { }
    }

    /** 根據 key 刪除 */
    public void delete(String key) {
        try {
            FileInputStream fis = new FileInputStream(filepath);
            properties.load(fis);
            Map<String, String> map = new HashMap<String, String>();
            Set<String> keys = properties.stringPropertyNames();
            for (String k : keys) {
                if (!k.equals(key)) {
                    map.put(k, properties.getProperty(k));
                }
            }
            OutputStream fos = new FileOutputStream(filepath);
            Properties newProps = new Properties();
            newProps.putAll(map);
            newProps.store(fos, null);
        } catch (IOException e) { }
    }
}

使用方式相當直觀:

// 取得物件;參數可以是檔案絕對路徑,也可以是 Context + 檔名
LocalStorage localStorage = LocalStorage.get("test.txt");

// 新增
localStorage.put("key", "哈哈");

// 更新
localStorage.update("key", "value");

// 查找,提供多個 getAs 方法對應不同型別
localStorage.getAsString("key");

// 刪除
localStorage.delete("key");
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved