FileInputStream:文件字節輸入流FileOutputStream:文件字節輸出流特點:無需 flush,底層直接操作字節,無緩衝區概念;關閉流即刷新。
public class FileStream {
// 1. 單字節讀取(極慢,教學用)
public static void readFile_0() throws IOException {
try (FileInputStream fis = new FileInputStream("fos.txt")) {
int ch;
while ((ch = fis.read()) != -1) System.out.print((char) ch);
}
}
// 2. 字節數組讀取(推薦,1024*N 最優)
public static void readFile_1() throws IOException {
try (FileInputStream fis = new FileInputStream("fos.txt")) {
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1) {
System.out.print(new String(buf, 0, len, "UTF-8"));
}
}
}
// 3. available() 一次性讀完(僅適用小文件,大文件 OOM 風險)
public static void readFile_2() throws IOException {
try (FileInputStream fis = new FileInputStream("fos.txt")) {
byte[] buf = new byte[fis.available()];
fis.read(buf);
System.out.print(new String(buf));
}
}
// 寫入示例
public static void writeFile() throws IOException {
try (FileOutputStream fos = new FileOutputStream("fos.txt")) {
fos.write("abc測試".getBytes("UTF-8"));
}
}
}
public class CopyPic {
public static void main(String[] args) {
try (FileInputStream fis = new FileInputStream("1.png");
FileOutputStream fos = new FileOutputStream("2.png")) {
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
} catch (Exception e) {
throw new RuntimeException("複製失敗", e);
}
}
}
核心邏輯:字節流「讀多少寫多少」,不做任何編碼轉換,保證二進制內容完全一致。
Q:字符流可以用於圖片複製嗎?
A:不可以。字符流按字符編碼讀取,遇到無對應字符的字節會替換為「替換字符」(),導致數據損壞;同理,字節流若錯誤截斷多字節字符也會產生亂碼。
BufferedReader / BufferedWriter(指定編碼)。BufferedInputStream / BufferedOutputStream(緩衝提速)。1024 * 4 (4KB) 或 1024 * 8 (8KB) 為宜,與磁盤塊大小對齊。