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

Android 文件讀寫工具類封裝

編輯:關於 Android 程式設計

這是一個長期維護的文件讀寫工具類,主要提供以下功能:

  1. 創建文件;
  2. 向文件寫入字節數組;
  3. 向文件寫入字符串;
  4. 從文件讀取字節數組;
  5. 從文件讀取字符串。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 文件讀寫工具類
 *
 * @author bear
 */
public class FileUtil {

    /**
     * 如果文件不存在,就創建文件
     *
     * @param path 文件路徑
     * @return 文件路徑
     */
    public static String createIfNotExist(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
        return path;
    }

    /**
     * 向文件中寫入數據
     *
     * @param filePath 目標文件全路徑
     * @param data     要寫入的數據
     * @return true 表示寫入成功,false 表示失敗
     */
    public static boolean writeBytes(String filePath, byte[] data) {
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(data);
            fos.close();
            return true;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return false;
    }

    /**
     * 從文件中讀取數據
     *
     * @param file 文件路徑
     * @return 字節數組
     */
    public static byte[] readBytes(String file) {
        try {
            FileInputStream fis = new FileInputStream(file);
            int len = fis.available();
            byte[] buffer = new byte[len];
            fis.read(buffer);
            fis.close();
            return buffer;
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 向文件中寫入字符串
     *
     * @param file     文件路徑
     * @param content  文件內容
     * @param charset  寫入時使用的字符集
     */
    public static void writeString(String file, String content, String charset) {
        try {
            byte[] data = content.getBytes(charset);
            writeBytes(file, data);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 從文件中讀取數據,返回字符串
     *
     * @param file    文件路徑
     * @param charset 讀取時使用的字符集,如 utf-8、GBK 等
     * @return 字符串內容
     */
    public static String readString(String file, String charset) {
        byte[] data = readBytes(file);
        String ret = null;
        try {
            ret = new String(data, charset);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return ret;
    }
}

這個工具類把字節流與字符串的讀寫細節統一封裝,業務代碼只需調用對應的靜態方法,並傳入合適的字符集,即可輕鬆完成文件的讀寫操作。

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