封裝常用文件 IO 操作,提供三大核心能力:
fileReaderStringHandle(String fileName)fileReaderByteHandle(String fileName)fileWriterHandle(String fileName, String text)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,獲得更好的性能、編碼安全性與異常處理能力。
來源:子孑博客