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

Android 檔案操作工具類分享:讀寫、複製、搜尋一次搞定

編輯:關於 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 加進清單。

SD 卡與目錄相關

這一段處理外部儲存的判斷與常用路徑:

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 關閉串流(上面已補上),才能避免檔案洩漏。把這些細節處理好,這個類就能安心地在你每個專案裡反覆使用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved