Android工具類之檔案操作工具類

陳李冠發表於2016-07-15

檔案,資料夾的建立、刪除、快取處理、base64加密、檔案大小格式化、讀取檔案內容、壓縮檔案…

package com.sunnybear.library.util;

import android.content.Context;
import android.os.Environment;
import android.util.Base64;

import com.sunnybear.library.BasicApplication;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 檔案操作工具
 * Created by Jusenr on 2016/12/10.
 */
public final class FileUtils {
    public static final String TAG = FileUtils.class.getSimpleName();
    public static final int BYTE = 1024;

    /**
     * 格式化單位
     *
     * @param size
     * @return
     */
    public static String getFormatSize(double size) {
        double kiloByte = size / BYTE;
        if (kiloByte < 1) {
            return size + "B";
        }

        double megaByte = kiloByte / BYTE;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / BYTE;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / BYTE;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);
        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    /**
     * 獲取快取檔案大小
     *
     * @param context
     * @return
     */
    public static String getTotalCacheSize(Context context) {
        long cacheSize = getFolderSize(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            cacheSize += getFolderSize(context.getExternalCacheDir());
        }
        return getFormatSize(cacheSize);
    }

    /**
     * 清除應用快取檔案
     *
     * @param context
     */
    public static void clearAllCache(Context context) {
        delete(context.getCacheDir());
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            delete(context.getExternalCacheDir());
        }
    }

    /**
     * 獲取檔案大小
     *
     * @param file
     * @return
     * @throws Exception
     */
    //Context.getExternalFilesDir() --> SDCard/Android/data/你的應用的包名/files/ 目錄,一般放一些長時間儲存的資料
    //Context.getExternalCacheDir() --> SDCard/Android/data/你的應用包名/cache/目錄,一般存放臨時快取資料
    public static long getFolderSize(File file) {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (int i = 0; i < fileList.length; i++) {
                // 如果下面還有檔案
                if (fileList[i].isDirectory()) {
                    size = size + getFolderSize(fileList[i]);
                } else {
                    size = size + fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 讀取檔案內容
     *
     * @param file    檔案
     * @param charset 檔案編碼
     * @return 檔案內容
     */
    public static String readFile(File file, String charset) {
        String fileContent = "";
        try {
            InputStreamReader read = new InputStreamReader(new FileInputStream(file), charset);
            BufferedReader reader = new BufferedReader(read);
            String line = "";
            int i = 0;
            while ((line = reader.readLine()) != null) {
                if (i == 0)
                    fileContent = line;
                else
                    fileContent = fileContent + "\n" + line;
                i++;
            }
            read.close();
        } catch (Exception e) {
            Logger.e("讀取檔案內容操作出錯", e);
        }
        return fileContent;
    }

    /**
     * 讀取檔案內容
     *
     * @param file 檔案
     * @return 檔案內容
     */
    public static String readFile(File file) {
        return readFile(file, "UTF-8");
    }

    /**
     * 獲取檔案的SHA1值
     *
     * @param file 目標檔案
     * @return 檔案的SHA1值
     */
    public static String getSHA1ByFile(File file) {
        if (file == null || !file.exists()) return "檔案不存在";
        long time = System.currentTimeMillis();
        InputStream in = null;
        String value = null;
        try {
            in = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            int numRead = 0;
            while (numRead != -1) {
                numRead = in.read(buffer);
                if (numRead > 0) digest.update(buffer, 0, numRead);
            }
            byte[] sha1Bytes = digest.digest();
            String t = new String(buffer);
            value = convertHashToString(sha1Bytes);
        } catch (Exception e) {
            Logger.e(e);
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    Logger.e(e);
                }
        }
        return value;
    }

    /**
     * @param hashBytes
     * @return
     */
    private static String convertHashToString(byte[] hashBytes) {
        String returnVal = "";
        for (int i = 0; i < hashBytes.length; i++) {
            returnVal += Integer.toString((hashBytes[i] & 0xff) + 0x100, 16).substring(1);
        }
        return returnVal.toLowerCase();
    }

    /**
     * 獲取上傳檔案的檔名
     *
     * @param filePath
     * @return
     */
    public static String getFileName(String filePath) {
        String filename = new File(filePath).getName();
        if (filename.length() > 80) {
            filename = filename.substring(filename.length() - 80, filename.length());
        }
        return filename;
    }

    /**
     * 建立資料夾
     *
     * @param mkdirs 資料夾
     */
    public static boolean createMkdirs(File mkdirs) {
        return mkdirs.mkdirs();
    }

    /**
     * 建立檔案
     *
     * @param file 檔案
     */
    public static boolean createFile(File file) {
        if (!file.exists()) {
            try {
                return file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            }
        }
        return false;
    }

    /**
     * 獲得下載檔名
     *
     * @param url 下載url
     * @return 檔名
     */
    public static String getDownloadFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    /**
     * 獲得應用的圖片儲存目錄
     *
     * @return
     */
    public static String getPicDirectory(Context context) {
        File picFile = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (picFile != null) {
            return picFile.getAbsolutePath();
        } else {
            return context.getFilesDir().getAbsolutePath() + "/Pictures";
        }
    }

    /**
     * 解壓assets的zip壓縮檔案到指定目錄
     *
     * @param context   上下文物件
     * @param assetName 壓縮檔名
     * @param outputDir 輸出目錄
     * @param isReWrite 是否覆蓋
     * @throws IOException
     */
    public static void unZipInAsset(Context context, String assetName, String outputDir, boolean isReWrite) throws IOException {
        String outputDirectory = BasicApplication.sdCardPath + File.separator + outputDir;
        // 建立解壓目標目錄
        File file = new File(outputDirectory);
        // 如果目標目錄不存在,則建立
        if (!file.exists()) file.mkdirs();
        // 開啟壓縮檔案
        InputStream inputStream = ResourcesUtils.getAssets(context).open(assetName);
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        // 讀取一個進入點
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        // 使用1Mbuffer
        byte[] buffer = new byte[1024 * 1024];
        // 解壓時位元組計數
        int count = 0;
        // 如果進入點為空說明已經遍歷完所有壓縮包中檔案和目錄
        while (zipEntry != null) {
            // 如果是一個目錄
            if (zipEntry.isDirectory()) {
                file = new File(outputDirectory + File.separator + zipEntry.getName());
                // 檔案需要覆蓋或者是檔案不存在
                if (isReWrite || !file.exists()) file.mkdir();
            } else {
                // 如果是檔案
                file = new File(outputDirectory + File.separator + zipEntry.getName());
                // 檔案需要覆蓋或者檔案不存在,則解壓檔案
                if (isReWrite || !file.exists()) {
                    file.createNewFile();
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    while ((count = zipInputStream.read(buffer)) > 0)
                        fileOutputStream.write(buffer, 0, count);
                    fileOutputStream.close();
                }
            }
            // 定位到下一個檔案入口
            zipEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.close();
    }

    /**
     * 解壓sdCard的zip壓縮檔案到指定目錄
     *
     * @param zipPath   壓縮檔案路徑
     * @param outputDir 輸出目錄
     * @param isReWrite 是否覆蓋
     * @throws IOException
     */
    public static void unZipInSdCard(String zipPath, String outputDir, boolean isReWrite) throws IOException {
        String outputDirectory = BasicApplication.sdCardPath + File.separator + outputDir;
        // 建立解壓目標目錄
        File file = new File(outputDirectory);
        // 如果目標目錄不存在,則建立
        if (!file.exists()) file.mkdirs();
        // 開啟壓縮檔案
        InputStream inputStream = new FileInputStream(new File(zipPath));
        ZipInputStream zipInputStream = new ZipInputStream(inputStream);
        // 讀取一個進入點
        ZipEntry zipEntry = zipInputStream.getNextEntry();
        // 使用1Mbuffer
        byte[] buffer = new byte[1024 * 1024];
        // 解壓時位元組計數
        int count = 0;
        // 如果進入點為空說明已經遍歷完所有壓縮包中檔案和目錄
        while (zipEntry != null) {
            // 如果是一個目錄
            if (zipEntry.isDirectory()) {
                file = new File(outputDirectory + File.separator + zipEntry.getName());
                // 檔案需要覆蓋或者是檔案不存在
                if (isReWrite || !file.exists()) file.mkdir();
            } else {
                // 如果是檔案
                file = new File(outputDirectory + File.separator + zipEntry.getName());
                // 檔案需要覆蓋或者檔案不存在,則解壓檔案
                if (isReWrite || !file.exists()) {
                    file.createNewFile();
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    while ((count = zipInputStream.read(buffer)) > 0)
                        fileOutputStream.write(buffer, 0, count);
                    fileOutputStream.close();
                }
            }
            // 定位到下一個檔案入口
            zipEntry = zipInputStream.getNextEntry();
        }
        zipInputStream.close();
    }

    /**
     * 刪除檔案
     *
     * @param filePath 檔案路徑
     * @return 是否刪除成功
     */
    public static boolean delete(String filePath) {
        File file = new File(filePath);
        return delete(file);
    }

    /**
     * 刪除檔案
     *
     * @param file 檔案
     * @return 是否刪除成功
     */
    public static boolean delete(File file) {
        if (file == null || !file.exists()) return false;
        if (file.isFile()) {
            final File to = new File(file.getAbsolutePath() + System.currentTimeMillis());
            file.renameTo(to);
            to.delete();
        } else {
            File[] files = file.listFiles();
            if (files != null && files.length > 0)
                for (File innerFile : files) {
                    delete(innerFile);
                }
            final File to = new File(file.getAbsolutePath() + System.currentTimeMillis());
            file.renameTo(to);
            return to.delete();
        }
        return false;
    }

    /**
     * 獲得檔案內容
     *
     * @param filePath 檔案路徑
     * @return 檔案內容
     */
    public static String getFileContent(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            try {
                BufferedReader br = new BufferedReader(new FileReader(file));//構造一個BufferedReader類來讀取檔案
                String result = null;
                String s = null;
                while ((s = br.readLine()) != null) {//使用readLine方法,一次讀一行
                    result = result + "\n" + s;
                }
                br.close();
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                Logger.e(e);
            }
        } else {
            return null;
        }
        return null;
    }

    /**
     * 儲存文字到檔案
     *
     * @param fileName 檔名字
     * @param content  內容
     * @param append   是否累加
     * @return 是否成功
     */
    public static boolean saveTextValue(String fileName, String content, boolean append) {
        try {
            File textFile = new File(fileName);
            if (!append && textFile.exists()) textFile.delete();
            FileOutputStream os = new FileOutputStream(textFile);
            os.write(content.getBytes("UTF-8"));
            os.close();
        } catch (Exception ee) {
            return false;
        }
        return true;
    }

    /**
     * 刪除目錄下所有檔案
     *
     * @param Path 路徑
     */
    public static void deleteAllFile(String Path) {
        // 刪除目錄下所有檔案
        File path = new File(Path);
        File files[] = path.listFiles();
        if (files != null)
            for (File tfi : files) {
                if (tfi.isDirectory())
                    System.out.println(tfi.getName());
                else
                    tfi.delete();
            }
    }

    /**
     * 儲存檔案
     *
     * @param in       檔案輸入流
     * @param filePath 檔案儲存路徑
     */
    public static File saveFile(InputStream in, String filePath) {
        File file = new File(filePath);
        byte[] buffer = new byte[4096];
        int len = 0;
        FileOutputStream fos = null;
        try {
            FileUtils.createFile(file);
            fos = new FileOutputStream(file);
            while ((len = in.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
        } catch (IOException e) {
            Logger.e(e);
        } finally {
            try {
                if (in != null) in.close();
                if (fos != null) fos.close();
            } catch (IOException e) {
                Logger.e(e);
            }
        }
        return file;
    }

    /**
     * 檔案是否存在
     *
     * @param path 檔案路徑
     * @return 檔案是否存在
     */
    public static boolean isExists(String path) {
        File file = new File(path);
        return file.exists();
    }

    /**
     * 檔案Base64加密
     *
     * @param path
     * @return
     */
    public static String fileToBase64String(String path) {
        FileInputStream inputStream = null;
        try {
            File file = new File(path);
            inputStream = new FileInputStream(file);
            byte[] fileBytes = new byte[inputStream.available()];
            inputStream.read(fileBytes);
            String base64String = Base64.encodeToString(fileBytes, Base64.DEFAULT);
            return base64String;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null)
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return null;
    }

    /**
     * 判斷檔案是否存在
     * 
     * @param strPath
     * @return
     */
    public boolean isExists(String strPath) {
        if (strPath == null) {
            return false;
        }

        final File strFile = new File(strPath);

        if (strFile.exists()) {
            return true;
        }
        return false;

    }
}

相關文章