android 超輕量級資料存放區類

來源:互聯網
上載者:User

android 超輕量級資料存放區類

這次可以和看了很不爽的sharedpreferences 說再見了。用法太噁心了。儲存屁大點資料還用 commit 。

 

吐槽結束,上代碼

 

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索引值對。提供增、刪、改、查方法。 可自訂路徑 *  * @author Administrator * */public class LocalStorage {private static Properties properties = new Properties();private static String filepath;private LocalStorage() {}/** *  * @param ctx * @param fileName *            檔案名稱 * @return */public static LocalStorage get(Context ctx, String fileName) {return get(ctx.getCacheDir() + "/" + fileName);}/** *  * @param filePath *            檔案絕對路徑 * @return */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;if (str.equals("true"))return true;return false;}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();}/** * 添加 *  * @param keyname * @param keyvalue */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) {}}/** * 更新 *  * @param keyname * @param keyvalue */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刪除 *  * @param key */public void delete(String key) {try {FileInputStream fis = new FileInputStream(filepath);properties.load(fis);Map map = new HashMap();Set keySet = properties.keySet();for (Object object : keySet) {String objectkey = (String) object;String value = (String) properties.get(objectkey);map.put(objectkey, value);}map.remove(key);properties.remove(key);for (java.util.Map.Entry entry : map.entrySet()) {properties.setProperty(entry.getKey(), entry.getValue());}FileOutputStream fos = new FileOutputStream(filepath);properties.store(fos, "delete key:" + key);fos.close();fis.close();} catch (Exception e) {e.printStackTrace();}}}


 

使用方法

 

 

// 這裡擷取LocalStorage對象。參數也可以為檔案絕對路徑,當然也可以直接傳入Context和檔案名稱。LocalStorage localStorage = LocalStorage.get("test.txt");// 增加localStorage.put("key", "哈哈");// 更新localStorage.update("key", "value");// 尋找,這裡提供多個getAs 方法。取資料找到相應的資料類型localStorage.getAsString("key");// 刪除localStorage.delete("key");


 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.