安卓資料持久化工具類總結
程式猿是最懶的生物,開發中從不重複造輪子,實際開發中資料吃就化是必然要處理的一個問題,先總結了幾個除處理sqlite外的幾個工具類,因為sqlite可以直接用orm,持久化資料有I/O,SharedPreference等等方式。
外置儲存卡
package cn.edu.zafu.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import android.os.Environment;/** * 外部存儲卡工具類 * 需要添加許可權 * android.permission.WRITE_EXTERNAL_STORAGE * android.permission.MOUNT_UNMOUNT_FILESYSTEMS * * @author lizhangqu * @version 1.0 * */public class ExternalStorageUtil {/** * 是否可寫 * * @return 可寫性 */public static boolean isExternalStorageWritable() {String state = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(state)) {return true;}return false;}/** * 是否可讀 * * @return 可讀性 */public static boolean isExternalStorageReadable() {String state = Environment.getExternalStorageState();if (Environment.MEDIA_MOUNTED.equals(state)|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {return true;}return false;}/** * 獲得根路徑 * * @return 外置記憶卡根路徑 */public static String getExternalStoragePath() {if (isExternalStorageWritable())return Environment.getExternalStorageDirectory().getAbsolutePath();elsereturn null;}/** * 獲得下載目錄路徑 * * @return 外置記憶卡下載路徑 */public static String getExternalDownloadPath() {return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();}/** * 向根路徑寫檔案 * * @param fileName 檔案名稱 * @param content 上下文 * @return 是否寫入成功 */public static boolean write(String fileName, String content) {return write("/", fileName, content);}/** * 向根目錄寫位元組 * * @param fileName 檔案名稱 * @param bytes 檔案位元組數組 * @return 是否寫入成功 */public static boolean writeBytes(String fileName, byte[] bytes) {return writeBytes("/", fileName, bytes);}/** * 向指定目錄的檔案中寫入字串,路徑以/開始/結尾 * * @param path 相對於根路徑的路徑,路徑以/開始,以/結尾 * @param fileName 檔案名稱 * @param content 檔案內容 * @return 是否寫入成功 */public static boolean write(String path, String fileName, String content) {return writeBytes(path, fileName, content.getBytes());}/** * 向指定目錄的檔案寫入位元組數組,路徑以/開始/結尾 * * @param path 相對於根路徑的路徑,路徑以/開始,以/結尾 * @param fileName 檔案名稱 * @param bytes 位元組數組 * @return */public static boolean writeBytes(String path, String fileName, byte bytes[]) {boolean flag = false;if (!path.equals("/")) {File dir = new File(getExternalStoragePath() + path);if (!dir.exists()) {if (!(dir.mkdir() || dir.isDirectory())) {// 檔案目錄建立失敗或者不是一個目錄return false;}}}File file = new File(getExternalStoragePath() + path + fileName);FileOutputStream fos = null;try {fos = new FileOutputStream(file, false);fos.write(bytes);flag = true;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fos != null) {try {fos.close();} catch (IOException e) {e.printStackTrace();}}}return flag;}/** * 從根路徑讀位元組 * * @param fileName 檔案名稱 * @return 位元組數組 */public static byte[] readBytes(String fileName) {return readBytes("/", fileName);}/** * 從指定目錄讀位元組,路徑以/開始/結尾 * * @param path 相對於根路徑的路徑,路徑以/開始,以/結尾 * @param fileName 檔案名稱 * @return 位元組數組 */public static byte[] readBytes(String path, String fileName) {File file = new File(getExternalStoragePath() + path + fileName);if (!file.isFile()) {return null;} else {FileInputStream fis = null;try {fis = new FileInputStream(file);int length = fis.available();byte[] buffer = new byte[length];fis.read(buffer);return buffer;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}return null;}}/** * 從根目錄讀文本 * * @param fileName 檔案名稱 * @return 字串 */public static String read(String fileName) {return read("/", fileName);}/** * 從指定目錄讀文本,路徑以/開始/結尾 * * @param path 相對於根路徑的路徑,路徑以/開始,以/結尾 * @param fileName 檔案名稱 * @return 字串 */public static String read(String path, String fileName) {try {byte[] readBytes = readBytes(path, fileName);if (readBytes == null) {return null;}return new String(readBytes, "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}/** * 從根目錄刪除 * * @param fileName 檔案名稱 * @return 是否刪除成功 */public static boolean delete(String fileName) {return delete("/", fileName);}/** * 從指定目錄刪除,路徑以/開始/結尾 * * @param path 相對於根路徑的路徑,路徑以/開始,以/結尾 * @param fileName 檔案名稱 * @return 是否刪除成功 */public static boolean delete(String path, String fileName) {File file = new File(getExternalStoragePath() + path + fileName);if (file.exists())return file.delete();elsereturn true;}}
內建儲存卡
package cn.edu.zafu.utils;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.UnsupportedEncodingException;import android.content.Context;/** * 內部存儲卡工具類 * * @author lizhangqu * @version 1.0 */public class InternalStorageUtil {/** * 在原檔案後追加內容 * * @param context 上下文 * @param fileName 檔案名稱 * @param content 追加的文本 * @return 是否追加成功 */public static boolean append(Context context, String fileName,String content) {return writeBytes(context, fileName, content.getBytes(), true);}/** * 寫入檔案,檔案存在則覆蓋 * * @param context 上下文 * @param fileName 檔案名稱 * @param content 寫入的文本 * @return 是否寫入成功 */public static boolean write(Context context, String fileName, String content) {return writeBytes(context, fileName, content.getBytes(), false);}/** * 寫入位元組 * * @param context 上下文 * @param fileName 檔案名稱 * @param content 寫入的位元組 * @return 是否寫入成功 */public static boolean writeBytes(Context context, String fileName,byte[] content) {return writeBytes(context, fileName, content, false);}/** * 寫入檔案,檔案存在時根據參數isAppend判斷是否覆蓋 * * @param context 上下文 * @param fileName 檔案名稱 * @param content 寫入的位元組 * @param isAppend 是否追加 * @return 是否寫入成功 */public static boolean writeBytes(Context context, String fileName,byte[] content, boolean isAppend) {FileOutputStream fout = null;boolean flag = false;try {if (isAppend) {fout = context.openFileOutput(fileName, Context.MODE_APPEND);} else {fout = context.openFileOutput(fileName, Context.MODE_PRIVATE);}fout.write(content);flag = true;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fout != null) {fout.close();fout = null;}} catch (IOException e) {e.printStackTrace();}}return flag;}/** * 讀取檔案 * * @param context 上下文 * @param fileName 檔案名稱 * @return 檔案內容的字串 */public static String read(Context context, String fileName) {byte[] buffer = readBytes(context, fileName);String result=null;try {result = new String(buffer, "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}/** * @param context 上下文 * @param fileName 檔案名稱 * @return 位元組數組 */public static byte[] readBytes(Context context, String fileName) {FileInputStream fin = null;byte[] buffer = null;try {fin = context.openFileInput(fileName);int length = fin.available();buffer = new byte[length];fin.read(buffer);} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fin != null) {fin.close();fin = null;}} catch (IOException e) {e.printStackTrace();}}return buffer;}/** * 清除所有檔案,當有一個檔案未清除時返回false * * @param context 上下文 * @return 是否清楚成功 */public static boolean clear(Context context) {boolean flag = true;String[] files = context.fileList();for (String fileName : files) {boolean result = context.deleteFile(fileName);if (result == false) {flag = false;}}return flag;}/** * 根據檔案名稱清除檔案 * * @param context 上下文 * @param fileName 檔案名稱 * @return 是否刪除成功 */public static boolean delete(Context context, String fileName) {return context.deleteFile(fileName);}/** * 返回內部儲存的絕對路徑 * * @param context 上下文 * @return app內建檔案夾路徑 */public static String getFileDir(Context context) {File filesDir = context.getFilesDir();return filesDir.getAbsolutePath();}}資源檔的讀取
package cn.edu.zafu.utils;import java.io.IOException;import java.io.InputStream;import java.io.UnsupportedEncodingException;import android.content.Context;/** * assert資源的讀取 * * @author lizhangqu * @version 1.0 */public class ResouceFileUtil {/** * 從assert檔案夾下讀取文本資源 * * @param context 上下文 * @param fileName 檔案名稱 * @return 檔案內容字串 */public static String readStringFromAssert(Context context, String fileName) {String result = null;byte[] buffer = readBytesFromAssert(context, fileName);try {result = new String(buffer, "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}/** * 從raw檔案夾下讀取文本資源 * * @param context 上下文 * @param rawId raw資源id * @return 檔案內容字串 */public static String readStringFromRaw(Context context, int rawId) {String result = null;byte[] buffer = readBytesFromRaw(context, rawId);try {result = new String(buffer, "UTF-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}/** * 從assert檔案夾下讀取檔案到位元組數組 * * @param context 上下文 * @param fileName 檔案名稱 * @return 檔案位元組數組 */public static byte[] readBytesFromAssert(Context context, String fileName) {InputStream is = null;byte[] buffer = null;try {is = context.getAssets().open(fileName);int size = is.available();buffer = new byte[size];is.read(buffer);} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();is = null;} catch (IOException e) {e.printStackTrace();}}}return buffer;}/** * 從raw檔案夾下讀取檔案到位元組數組 * * @param context 上下文 * @param rawId raw資源id * @return 檔案位元組數組 */public static byte[] readBytesFromRaw(Context context, int rawId) {InputStream is = null;byte[] buffer = null;try {is = context.getResources().openRawResource(rawId);int size = is.available();buffer = new byte[size];is.read(buffer);} catch (IOException e) {e.printStackTrace();} finally {if (is != null) {try {is.close();is = null;} catch (IOException e) {e.printStackTrace();}}}return buffer;}}
SharedPreference的操作
package cn.edu.zafu.utils;import android.content.Context;import android.content.SharedPreferences;/** * SharedPreference方式持久化資料的工具類 * * @author lizhangqu * @version 1.0 */public class SharedPreferenceUtil {/** * 儲存索引值對 * * @param context 上下文 * @param fileName 檔案名稱 * @param key 鍵 * @param value 值 * @return 是否儲存成功 */public static boolean set(Context context, String fileName, String key,String value) {SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPreferences.edit();editor.putString(key, value);return editor.commit();}/** * 獲得鍵對應的值,如果沒有則返回"" * * @param context 上下文 * @param fileName 檔案名稱 * @param key 鍵 * @return 值,沒有則返回"" */public static String get(Context context, String fileName, String key) {return get(context, fileName, key, "");}/** * 獲得鍵對應的值,如果沒有則返回defaultValue * * @param context 上下文 * @param fileName 檔案名稱 * @param key 鍵 * @param defaultValue 預設值 * @return 值,沒有則返回defaultValue */public static String get(Context context, String fileName, String key,String defaultValue) {SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);String value = sharedPreferences.getString(key, defaultValue);// 第二個參數為預設值return value;}/** * 移除一項 * @param context 上下文 * @param fileName 檔案名稱 * @param key 鍵 * @return 是否移除成功 */public static boolean remove(Context context, String fileName, String key) {SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPreferences.edit();editor.remove(key);return editor.commit();}/** * 清除檔案內容 * @param context 上下文 * @param fileName 檔案名稱 * @return 是否清除成功 */public static boolean clear(Context context, String fileName) {SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPreferences.edit();editor.clear();return editor.commit();}/** * 某一項是否存在 * @param context 上下文 * @param fileName 檔案名稱 * @param key 鍵 * @return 該鍵對應的值是否存在 */public static boolean contatins(Context context, String fileName,String key) {SharedPreferences sharedPreferences = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);return sharedPreferences.contains(key);}}