Android之檔案讀寫工具類

來源:互聯網
上載者:User

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;}}


 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.