編輯:關於 Android 程式設計
開發中資料持久化是繞不開的一環。除了可以直接搭配 ORM 使用的 SQLite,Android 還提供了檔案 I/O 與 SharedPreferences 等方式。以下整理四個可直接複用的工具類。
需要權限:android.permission.WRITE_EXTERNAL_STORAGE、android.permission.MOUNT_UNMOUNT_FILESYSTEMS。
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;
/**
* 外部儲存卡工具類
*
* @author lizhangqu
* @version 1.0
*/
public class ExternalStorageUtil {
/** 是否可寫 */
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/** 是否可讀 */
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;
}
/** 取得外部儲存卡根路徑 */
public static String getExternalStoragePath() {
if (isExternalStorageWritable()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
} else {
return null;
}
}
/** 取得下載目錄路徑 */
public static String getExternalDownloadPath() {
return Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
}
/** 向根路徑寫入字串 */
public static boolean write(String fileName, String content) {
return write("/", fileName, content);
}
/** 向根路徑寫入位元組 */
public static boolean writeBytes(String fileName, byte[] bytes) {
return writeBytes("/", fileName, bytes);
}
/** 向指定目錄寫入字串,path 以 / 開頭結尾 */
public static boolean write(String path, String fileName, String content) {
return writeBytes(path, fileName, content.getBytes());
}
/** 向指定目錄寫入位元組陣列 */
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;
}
/** 從根路徑讀位元組 */
public static byte[] readBytes(String fileName) {
return readBytes("/", fileName);
}
/** 從指定目錄讀位元組 */
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;
}
}
/** 從根目錄讀文字 */
public static String read(String fileName) {
return read("/", fileName);
}
/** 從指定目錄讀文字 */
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;
}
/** 從根目錄刪除 */
public static boolean delete(String fileName) {
return delete("/", fileName);
}
/** 從指定目錄刪除 */
public static boolean delete(String path, String fileName) {
File file = new File(getExternalStoragePath() + path + fileName);
if (file.exists()) {
return file.delete();
} else {
return 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 {
/** 在原檔案後追加內容 */
public static boolean append(Context context, String fileName, String content) {
return writeBytes(context, fileName, content.getBytes(), true);
}
/** 寫入檔案,存在則覆蓋 */
public static boolean write(Context context, String fileName, String content) {
return writeBytes(context, fileName, content.getBytes(), false);
}
/** 寫入位元組 */
public static boolean writeBytes(Context context, String fileName, byte[] content) {
return writeBytes(context, fileName, content, false);
}
/** 依 isAppend 決定覆蓋或追加 */
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;
}
/** 讀取檔案 */
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;
}
/** 讀取檔案為位元組陣列 */
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 */
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;
}
/** 依檔名刪除檔案 */
public static boolean delete(Context context, String fileName) {
return context.deleteFile(fileName);
}
/** 回傳內部儲存的絕對路徑 */
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;
/**
* assets 資源的讀取
*
* @author lizhangqu
* @version 1.0
*/
public class ResouceFileUtil {
/** 從 assets 讀取文字 */
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 讀取文字 */
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;
}
/** 從 assets 讀取檔案為位元組陣列 */
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 讀取檔案為位元組陣列 */
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;
}
}
package cn.edu.zafu.utils;
import android.content.Context;
import android.content.SharedPreferences;
/**
* SharedPreference 方式持久化資料的工具類
*
* @author lizhangqu
* @version 1.0
*/
public class SharedPreferenceUtil {
/** 保存鍵值對 */
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();
}
/** 取得鍵對應的值,沒有則回傳空字串 */
public static String get(Context context, String fileName, String key) {
return get(context, fileName, key, "");
}
/** 取得鍵對應的值,沒有則回傳 defaultValue */
public static String get(Context context, String fileName, String key, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
fileName, Context.MODE_PRIVATE);
return sharedPreferences.getString(key, defaultValue);
}
/** 移除一項 */
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();
}
/** 清除檔案內容 */
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();
}
/** 判斷某一項是否存在 */
public static boolean contatins(Context context, String fileName, String key) {
SharedPreferences sharedPreferences = context.getSharedPreferences(
fileName, Context.MODE_PRIVATE);
return sharedPreferences.contains(key);
}
}
內部儲存(getFilesDir())不對外暴露,適合存放私有資料,容量受限於 App 的可用空間;外部儲存適合放較大的檔案或需要與其他應用共享的內容,但從 Android 10 起受 Scoped Storage 規範,建議改用 getExternalFilesDir();assets 與 raw 都是唯讀的隨包資源,raw 支援 openRawResourceFd() 可直接餵給 MediaPlayer,較大的媒體檔放 raw 更方便;SharedPreferences 則適合設定值等小型鍵值資料,資料量大時應改用資料庫。另外範例中的 commit() 是同步寫入,若在主執行緒頻繁呼叫會卡 UI,可替換為 apply()。
從四個方法理清 Android 觸摸事件的分發與消費機制
提到 Android 的觸摸事件處理,很多人第一反應就是那幾個「令人頭疼」的方法: @Override public boolean onTouchEvent(Moti
Android Root 原理剖析:su 機制、SUID 與 adbd 降權缺陷
「Root 破解」聽起來神秘,但把原始碼攤開來看,它的核心其實只有一個動作:換掉系統裡的 su。以下從機制層面說明它為何可行,以及當年那個著名的提權缺陷是怎麼被補上的。這
Android Graphics(五):drawText() 原點與基線完全解析
前言:但行好事,莫問前程,只需努力每一天。 一、從四線格說起 1、四線格與基線 小時候剛學寫字母,本子都是四線格的,字母必須按規則寫在格子裡。 Canvas 用 dr
MPAndroidChart 折線圖實作詳解:初始化、資料設定與更新
MPAndroidChart 是 Android 上常用的圖表庫,支援折線圖、長條圖、圓餅圖等多種圖表。本文以折線圖為例,說明初始化、資料設定、更新與 x 軸資料處理方式