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

Android 文件操作工具類封裝詳解

編輯:關於 Android 程式設計

在 Android 開發中,文件的讀寫、拷貝與刪除是再常見不過的需求。下面這個 FileUtils 工具類把這些操作做了統一封裝:當存在 SD 卡時數據從 SD 卡讀寫,否則退回通過應用的 DATA 目錄讀寫,十分實用。

package cn.ibabyzone.library;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.os.Environment;
import android.util.Log;
// 用戶數據讀寫函數:存在 SD 卡時數據從 SD 卡讀寫,不存在時通過 DATA 目錄讀寫
public class FileUtils {
    private String SDPATH;
    private int FILESIZE = 1;
    public String getSDPATH() {
        return SDPATH;
    }
    public FileUtils(Activity thisActivity) {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            SDPATH = Environment.getExternalStorageDirectory() + "/ibabyzone/";
        } else {
            SDPATH = thisActivity.getFilesDir().toString() + "/ibabyzone/";
        }
    }
    /** 在 SD 卡上創建文件 */
    public File creatSDFile(String fileName) throws IOException {
        File file = new File(SDPATH + fileName);
        file.createNewFile();
        return file;
    }
    public void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); // 刪除裡面所有內容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); // 刪除空文件夾
        } catch (Exception e) {
            System.out.println("刪除文件夾操作出錯");
            e.printStackTrace();
        }
    }
    /** 刪除文件夾裡面的所有文件 */
    public void delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]); // 先刪除文件夾裡面的文件
                delFolder(path + "/" + tempList[i]);  // 再刪除空文件夾
            }
        }
    }
    /** 在 SD 卡上創建目錄 */
    public File creatSDDir(String dirName) {
        File dir = new File(SDPATH + dirName);
        dir.mkdir();
        return dir;
    }
    /** 判斷 SD 卡上的文件夾是否存在 */
    public boolean isFileExist(String fileName) {
        File file = new File(SDPATH + fileName);
        return file.exists();
    }
    public long file_time(String fileName) {
        File file = new File(SDPATH + fileName);
        return file.lastModified();
    }
    /** 將一個 InputStream 裡面的數據寫入到 SD 卡中 */
    public File write2SDFromInput(String path, String fileName, InputStream input) {
        File file = null;
        OutputStream output = null;
        try {
            creatSDDir(path);
            file = creatSDFile(path + fileName);
            output = new FileOutputStream(file);
            byte[] buffer = new byte[FILESIZE];
            while ((input.read(buffer)) != -1) {
                output.write(buffer);
            }
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }
    public static void deleteFile(String fileStr) {
        File file = new File(fileStr);
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            }
            file.delete();
        }
    }
    public void delFile(String path) {
        String str = SDPATH + path;
        File file = new File(str);
        if (file.exists()) {
            file.delete();
        }
    }
    public int CopyFileToFile(File fromFile, File toFile) {
        try {
            InputStream fosfrom = new FileInputStream(fromFile);
            OutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            return 0;
        } catch (Exception ex) {
            return -1;
        }
    }
    public File CopyFileRomToSD(String romfile) {
        if (!android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            return null;
        }
        File rom = new File(romfile);
        File sd = new File(Environment.getExternalStorageDirectory() + "/ibabyzone/" + romfile);
        if (CopyFileToFile(rom, sd) == 0) {
            return sd;
        }
        return null;
    }
}

這個工具類涵蓋了文件的創建、目錄管理、流寫入、拷貝與遞歸刪除等常用操作,並通過判斷外部存儲是否掛載來自動選擇讀寫路徑,可直接複用於實際項目。

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