編輯:關於 Android 程式設計
做 Android 專案時,檔案的讀寫、刪除、複製、搜尋、判斷存在與否這些動作幾乎每個 App 都會用到。與其每次重寫,不如把它們全部封裝成一個工具類,之後隨取隨用。下面這個 FileAdapter 就是這樣的整理,順便留著以後參考。
第一個實用的是「掃描某目錄、取出指定副檔名的檔案」。這裡用 AsyncTask 把遞迴掃描丟到背景執行緒,避免阻塞 UI,掃完再透過回呼介面把結果送回來:
public class FileAdapter {
private static final String TAG = "FileAdaptor";
/**
* 獲取指定位置的指定類型的文件
* @param path 文件夾路徑
* @param type 文件類型(如 "jpg")
*/
public static void getFileList(String path, String type,
final OnFileListCallback onFileListCallback) {
new AsyncTask<String, String, String>() {
ArrayList<FileInfo> list = new ArrayList<FileInfo>();
@Override
protected void onPostExecute(String result) {
onFileListCallback.SearchFileListInfo(list);
}
@Override
protected String doInBackground(String... params) {
String ext = params[1].substring(params[1].lastIndexOf(".") + 1);
File file = new File(params[0]);
scanSDCard(file, ext, list);
return null;
}
}.execute(path, type, "");
}
// 掃描完成後的回調,取得檔案清單時必須實作
public interface OnFileListCallback {
public void SearchFileListInfo(List<FileInfo> list);
}
}
真正的遞迴掃描放在 scanSDCard:遇到目錄就往下鑽,遇到檔案就比對副檔名,符合的包成 FileInfo 加進清單。
這一段處理外部儲存的判斷與常用路徑:
public static boolean isSdCardExist() {
return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
public static String getSdCardRootDir() {
return Environment.getExternalStorageDirectory().getPath() + "/";
}
public static String getCacheDir(Context ctx) {
return ctx.getCacheDir().getPath() + "/"; // /data/data//cache
}
public static String getFilesDir(Context ctx) {
return ctx.getFilesDir().getPath() + "/"; // /data/data//files
}
public static boolean mkDir(String path) {
File dir = new File(path);
return dir.mkdirs();
}
把一個 InputStream 的內容寫進指定路徑,用緩衝區一塊一塊搬,效能比逐位元組讀上好得多。這裡也用 try/finally 確保串流一定會被關掉:
public static boolean writeFile(String path, InputStream is) {
boolean result = false;
FileOutputStream os = null;
BufferedOutputStream bos = null;
try {
File file = new File(path);
os = new FileOutputStream(file, false);
bos = new BufferedOutputStream(os);
int readLen = 0;
byte[] buf = new byte[1024];
while ((readLen = is.read(buf)) != -1) {
bos.write(buf, 0, readLen);
}
bos.flush();
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bos != null) bos.close();
if (os != null) os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
// 直接寫入一段文字
public static boolean writeTextFile(String path, String data) {
boolean result = false;
FileWriter fw = null;
try {
File file = new File(path);
fw = new FileWriter(file);
fw.write(data);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (fw != null) fw.close(); } catch (Exception e) { e.printStackTrace(); }
}
return result;
}
// 讀檔,回傳串流
public static InputStream readFile(String path) {
File file = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (Exception e) { }
return fis;
}
複製就是「一邊讀、一邊寫」,無論是一般檔案還是從 assets 複出來,套路都一樣:
public static boolean CopyFile(String fromFile, String toFile) {
try {
InputStream fosfrom = new FileInputStream(fromFile);
OutputStream fosto = new FileOutputStream(toFile);
byte bt[] = new byte[4096];
int c;
while ((c = fosfrom.read(bt)) > 0) {
fosto.write(bt, 0, c);
}
fosfrom.close();
fosto.close();
bt = null;
return true;
} catch (Exception ex) {
return false;
}
}
public static boolean deleteFile(String path) {
try {
File file = new File(path);
return file.delete();
} catch (Exception ex) {
return false;
}
}
public static boolean isFileExist(String path) {
try {
File file = new File(path);
return file.exists();
} catch (Exception ex) { }
return false;
}
這個工具類把常見檔案操作都攏來了,很適合直接複製到自己的專案再依需求微調。要特別注意的是:其一,涉及外部儲存時別忘了在 Manifest 開 WRITE_EXTERNAL_STORAGE 權限並處理執行期授權;其二,原範例的 getSharedPrefDir 把套件名稱寫死了,實際使用時應改成動態取得;其三,writeFile 這類方法建議一律用 finally 關閉串流(上面已補上),才能避免檔案洩漏。把這些細節處理好,這個類就能安心地在你每個專案裡反覆使用。
React Native 原生模块开发实战笔记(Android / iOS)
目录: 环境: Mac、Xcode、WebStorm、Android Studio node v6.4.0 react-native-cli: 1.0.0 react-
如何快速搭好 Android 開發環境:JDK 與 ADT Bundle 配置
環境準備概述 建立 Android 開發環境時,通常需要先安裝 JDK,再準備 Eclipse 與 ADT Bundle。較舊的 ADT Bundle 可能內建部分系統映
在 App 裡即時攔截 logcat:一個被低估的除錯技巧
這個技巧來自一段通宵趕工的經驗,卻意外好用:讓程式自己去讀 logcat,即時監聽某段日誌。 為什麼需要它?因為 Android 各家廠商對系統做了各種客製,機型之間差異
Retrofit + OkHttp + RxAndroid 實戰:從網路請求到快取與攔截
為什麼選擇 Retrofit、OkHttp 與 RxAndroid 在 Android 網路開發中,OkHttp 提供了強大的連線與攔截能力,Retrofit 則把 HT