InputStream。OutputStream,支持追加模式。均可通過 File、String path、FileDescriptor 三種方式構造。
FileInputStream(File file)
FileInputStream(FileDescriptor fd)
FileInputStream(String path)
int read() // 讀單字節,返回 int (0-255 或 -1)
int read(byte[] b, int off, int len) // 批量讀取
long skip(long n) // 跳過字節
int available() // 可讀字節估算
FileChannel getChannel() // 獲取 NIO 通道
FileDescriptor getFD() // 獲取文件描述符
FileOutputStream(File file) // 默認覆蓋
FileOutputStream(File file, boolean append) // append=true 追加
FileOutputStream(String path)
FileOutputStream(String path, boolean append)
FileOutputStream(FileDescriptor fd)
void write(int b) // 寫單字節
void write(byte[] b, int off, int len) // 批量寫入
FileChannel getChannel()
FileDescriptor getFD()
File file = new File("file.txt");
// 首次寫入:覆蓋模式寫入字母
try (PrintStream out = new PrintStream(new FileOutputStream(file))) {
out.print("abcdefghijklmnopqrstuvwxyz");
}
// 二次寫入:追加模式寫入數字
try (PrintStream out = new PrintStream(new FileOutputStream(file, true))) {
out.println("0123456789");
}
// 文件內容:abcdefghijklmnopqrstuvwxyz0123456789
// 若二次改為 false,文件僅剩 0123456789
try (FileInputStream in1 = new FileInputStream(file);
FileInputStream in2 = new FileInputStream(file);
FileInputStream in3 = new FileInputStream(in2.getFD());
BufferedInputStream bin = new BufferedInputStream(in3)) {
char c1 = (char) in1.read(); // 'a'
in1.skip(25); // 跳過 b~z
byte[] buf = new byte[10];
in1.read(buf); // 讀取 0123456789
System.out.println(new String(buf));
char c2 = (char) bin.read(); // 'a' (緩衝流獨立位置)
}
注意:同一文件的多個流擁有獨立的文件指針,互不影響。
FileInputStream/OutputStream 是文件字節操作的基石。關鍵點:構造時選擇追加模式、善用 getFD() 實現流切換、配合 BufferedXxx 提升性能、結合 NIO FileChannel 實現零拷貝/內存映射。