首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java IO 操作工具類封裝:文件讀寫、字符串/字節數組轉換最佳實踐

     編輯:Java 相關知識

工具類設計目標

封裝常用文件 IO 操作,提供三大核心能力:

  • 文件 → 字符串:fileReaderStringHandle(String fileName)
  • 文件 → 字節數組:fileReaderByteHandle(String fileName)
  • 字符串 → 文件:fileWriterHandle(String fileName, String text)

核心實現代碼 (IOUtil.java)

import java.io.*;
import java.nio.file.*;

public class IOUtil {

    /** 讀取文件為字符串:FileReader + BufferedReader (支援 readLine) */
    public static String fileReaderStringHandle(String fileName) {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader in = new BufferedReader(
                new FileReader(new File(fileName).getAbsoluteFile()))) {
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
            throw new RuntimeException("讀取文件失敗: " + fileName, e);
        }
        return sb.toString();
    }

    /** 讀取文件為字節數組:FileInputStream + BufferedInputStream */
    public static byte[] fileReaderByteHandle(String fileName) {
        try (BufferedInputStream bis = new BufferedInputStream(
                new FileInputStream(fileName))) {
            byte[] data = new byte[bis.available()];
            int read = bis.read(data);
            return (read == -1) ? new byte[0] : data;
        } catch (IOException e) {
            throw new RuntimeException("讀取字節失敗: " + fileName, e);
        }
    }

    /** 寫入字符串到文件:PrintWriter */
    public static void fileWriterHandle(String fileName, String text) {
        try (PrintWriter out = new PrintWriter(
                new File(fileName).getAbsoluteFile())) {
            out.print(text);
        } catch (IOException e) {
            throw new RuntimeException("寫入文件失敗: " + fileName, e);
        }
    }

    // 測試主方法
    public static void main(String[] args) throws IOException {
        String content = fileReaderStringHandle("src/IOUtil.java");
        System.out.print(content);

        for (byte b : fileReaderByteHandle("src/IOUtil.java"))
            System.out.print(b);

        fileWriterHandle("zj.txt", content);
    }
}

關鍵設計亮點與改進建議

✅ 現代化資源管理

採用 try-with-resources (Java 7+) 自動關閉流,取代原始碼中的手動 finally 塊,代碼更簡潔、安全。

⚠️ 原始碼潛在問題

  • bf.available() 返回剩餘可讀字節數,不等於文件總長度(網絡流/管道流無效),大文件可能讀取不全
  • 缺乏字符集指定,跨平台易產生亂碼
  • 異常包裹為 RuntimeException 導致檢查型異常丟失,調用方無法針對性處理

🚀 生產級增強版建議

// 指定 UTF-8 編碼,支援大文件分塊讀取
public static String readFile(String path, Charset charset) throws IOException {
    return Files.readString(Paths.get(path), charset);
}

public static byte[] readAllBytes(String path) throws IOException {
    return Files.readAllBytes(Paths.get(path)); // NIO.2 高效實現
}

public static void writeString(String path, String content, Charset charset) throws IOException {
    Files.writeString(Paths.get(path), content, charset, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
}

總結

該工具類展示了經典 IO 流組合模式,適合教學與簡單場景。生產環境建議遷移至 java.nio.file.Files API,獲得更好的性能、編碼安全性與異常處理能力。

來源:子孑博客

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved