Android之檔案讀寫工具類
本工具類永久維護,永久更新,如果各位讀者發現有bug或者不合理之處,歡迎指正,博主將第一時間改正。
以下是主要內容,本類主要功能有:
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;}/** * 向檔案中寫入字串String類型的內容 * * @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());}}/** * 從檔案中讀取資料,傳回型別是字串String類型 * * @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;}}