Java文件與IO流詳細(xì)攻略
導(dǎo)讀:為什么要學(xué) IO 流?
- 程序要與“外部世界”交互——讀寫文件、網(wǎng)絡(luò)傳輸、控制臺(tái)輸入輸出,本質(zhì)都是“數(shù)據(jù)流”。
- Java 提供了兩大類 IO:
- 字節(jié)流:
InputStream/OutputStream(處理二進(jìn)制:圖片、音頻、視頻、任意文件) - 字符流:
Reader/Writer(處理文本:txt、md、json、java 源碼等)
- 字節(jié)流:
- 記憶口訣:
- “看得懂的是字符流(文本),看不懂的是字節(jié)流(二進(jìn)制)”。
- “文本優(yōu)先用字符流,其他都用字節(jié)流,拿不準(zhǔn)選字節(jié)流”。
基石:File 類(文件與目錄)
java.io.File 不是“文件內(nèi)容”,而是“文件或目錄的路徑抽象”。常見用法:
import java.io.File;
public class FileBasicsDemo {
public static void main(String[] args) {
// 1) 路徑與構(gòu)造
File file = new File("D:/IO/hello.txt"); // 建議使用 / 或者使用 Paths 構(gòu)建
File dir = new File("D:/IO/sub");
// 2) 基本信息
System.out.println(file.getAbsolutePath());
System.out.println(file.getName());
System.out.println(file.exists());
System.out.println(file.isFile());
System.out.println(file.isDirectory());
// 3) 創(chuàng)建目錄/文件
if (!dir.exists()) {
boolean ok = dir.mkdirs(); // 遞歸創(chuàng)建目錄
System.out.println("mkdirs: " + ok);
}
// 創(chuàng)建新文件(若父目錄不存在會(huì)失?。?
try {
if (!file.exists()) {
boolean created = file.createNewFile();
System.out.println("createNewFile: " + created);
}
} catch (Exception e) {
e.printStackTrace();
}
// 4) 遍歷目錄
File root = new File("D:/IO");
File[] children = root.listFiles();
if (children != null) {
for (File f : children) {
System.out.println((f.isDirectory() ? "[DIR] " : "[FILE]") + f.getName());
}
}
}
}提示:在 Windows 上用 "D:/path/file.txt" 更穩(wěn)妥,避免 \\ 轉(zhuǎn)義麻煩。生產(chǎn)代碼推薦 java.nio.file.Paths 與 Files(NIO.2),本文以 IO 基礎(chǔ)為主。
兩大體系的核心區(qū)別
- 字節(jié)流(8-bit):
InputStream/OutputStream,按“字節(jié)”處理,適合任何數(shù)據(jù); - 字符流(16-bit):
Reader/Writer,按“字符”處理,關(guān)注“編碼”,適合文本; - 關(guān)系:字符流往往是“基于字節(jié)流 + 編碼解碼器(
InputStreamReader/OutputStreamWriter)”。
字符流(Reader/Writer):處理文本最順手
1)字符輸入:Reader 家族
Reader:抽象基類- 常見實(shí)現(xiàn):
FileReader:快捷讀取文件文本(使用平臺(tái)默認(rèn)編碼,不建議在生產(chǎn)環(huán)境依賴默認(rèn)編碼)InputStreamReader:橋接器,將字節(jié)流解碼為字符流,可指定編碼(推薦)BufferedReader:帶緩沖、支持readLine(),高效讀取
修正與提升后的綜合示例(包含三種讀取方式,改為 try-with-resources、指定編碼、健壯性更好):
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ReaderDemo {
public static void main(String[] args) {
String path = "D:/IdeaProjects/JavaTest/src/com/qcby/a.txt";
// 1) FileReader:簡(jiǎn)單,但依賴平臺(tái)默認(rèn)編碼(不推薦在生產(chǎn)使用)
try (FileReader reader = new FileReader(path)) {
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
// 2) InputStreamReader:可指定編碼(推薦)
try (InputStreamReader reader = new InputStreamReader(
new FileInputStream(path), StandardCharsets.UTF_8)) {
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
// 3) BufferedReader:高效且支持按行讀取
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}說明:
FileReader與FileWriter在編碼未知或跨平臺(tái)時(shí)不夠穩(wěn)妥,實(shí)際開發(fā)更推薦InputStreamReader/OutputStreamWriter并顯式指定編碼。
2)字符輸出:Writer 家族
Writer:抽象基類- 常見實(shí)現(xiàn):
FileWriter:快捷寫文本(默認(rèn)編碼,不建議長(zhǎng)期依賴)OutputStreamWriter:橋接器,將字符流編碼為字節(jié)流,可指定編碼(推薦)BufferedWriter:帶緩沖、newLine()友好換行
綜合示例(修正:使用 try-with-resources,必要時(shí) flush/close,路徑與編碼更明確):
import java.io.*;
import java.nio.charset.StandardCharsets;
public class WriterDemo {
public static void main(String[] args) {
String outPath = "D:/IO/output.txt";
// 1) FileWriter:簡(jiǎn)單寫文本
try (FileWriter writer = new FileWriter(outPath)) { // 默認(rèn)編碼
writer.write("Hello, World!\n");
writer.write("This is a new line.\n");
} catch (IOException e) {
e.printStackTrace();
}
// 2) OutputStreamWriter:指定編碼(推薦)
try (OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(outPath, true), StandardCharsets.UTF_8)) { // 追加寫
writer.write("追加一行,使用UTF-8編碼。\n");
} catch (IOException e) {
e.printStackTrace();
}
// 3) BufferedWriter:高效按行寫
try (BufferedWriter bw = new BufferedWriter(new FileWriter(outPath, true))) {
bw.write("Hello, World!");
bw.newLine();
bw.write("This is a new line.");
} catch (IOException e) {
e.printStackTrace();
}
}
}3)Writer 的五種write方法(快速對(duì)照)
write(int c):寫入單個(gè)字符(低 16 位有效)write(char[] cbuf):寫入字符數(shù)組write(char[] cbuf, int off, int len):寫入字符數(shù)組的一部分write(String str):寫入字符串write(String str, int off, int len):寫入字符串的一部分
示例(修正筆記,補(bǔ)全導(dǎo)入與路徑):
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class WriterExample {
public static void main(String[] args) {
String out = "D:/IO/writer-demo.txt";
try (Writer writer = new FileWriter(out)) {
// 1. 寫入單個(gè)字符
writer.write('H');
// 2. 寫入字符數(shù)組
char[] array = {'e', 'l', 'l', 'o'};
writer.write(array);
// 3. 寫入字符數(shù)組的一部分(寫入 "ll")
writer.write(array, 2, 2);
// 4. 寫入字符串
writer.write(", World!");
// 5. 寫入字符串的一部分(寫入 "This is Java")
String str = "\nThis is Java IO.";
writer.write(str, 1, 12);
System.out.println("數(shù)據(jù)已寫入文件!");
} catch (IOException e) {
e.printStackTrace();
}
}
}字節(jié)流(InputStream/OutputStream):萬能讀寫器
1)字節(jié)輸入:InputStream 家族
- 核心方法:
int read():讀 1 字節(jié)(0-255),EOF 返回 -1int read(byte[] b):批量讀取到數(shù)組,返回本次讀取長(zhǎng)度或 -1int read(byte[] b, int off, int len):從 off 開始最多讀 len 個(gè)字節(jié)void close():關(guān)閉流并釋放資源
- 常見實(shí)現(xiàn):
FileInputStream、BufferedInputStream、ByteArrayInputStream等
基于筆記修正后的示例:
import java.io.*;
import java.nio.charset.StandardCharsets;
public class FileInputStreamTest {
public static void main(String[] args) {
File file = new File("D:/IO/hello.txt");
// 建議:優(yōu)先使用 try-with-resources,避免手動(dòng) finally 關(guān)閉
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int len;
while ((len = fis.read(buffer)) != -1) {
// 如果是文本,可按編碼構(gòu)造字符串;若是二進(jìn)制,直接處理字節(jié)
String chunk = new String(buffer, 0, len, StandardCharsets.UTF_8);
System.out.print(chunk);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}注意:如果文件不是 UTF-8 文本,上面把字節(jié)解碼為字符串可能出現(xiàn)亂碼。處理圖片/音頻/視頻等二進(jìn)制文件時(shí),不要把字節(jié)強(qiáng)行轉(zhuǎn)成字符串。
2)字節(jié)輸出:OutputStream 家族
- 核心方法:
void write(int b):寫 1 個(gè)字節(jié)(低 8 位有效)void write(byte[] b):寫入整個(gè)字節(jié)數(shù)組void write(byte[] b, int off, int len):寫入數(shù)組的一部分void flush():刷新緩沖區(qū)(有緩沖的輸出流/Writer)void close():關(guān)閉流并釋放資源
- 常見實(shí)現(xiàn):
FileOutputStream、BufferedOutputStream、ByteArrayOutputStream等
增強(qiáng)示例(追加寫入、換行、片段寫入):
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
public class FileOutputStreamTest {
public static void main(String[] args) {
File file = new File("D:/IO/hello.txt");
// true 表示追加寫
try (FileOutputStream fos = new FileOutputStream(file, true)) {
fos.write(97); // 寫入單字節(jié) 'a'
fos.write("\r\n".getBytes(StandardCharsets.UTF_8));
fos.write("中國(guó)人!\r\n".getBytes(StandardCharsets.UTF_8));
fos.write("ABCDEFGH".getBytes(StandardCharsets.UTF_8), 2, 4); // 輸出 CDEF
} catch (IOException e) {
e.printStackTrace();
}
}
}Windows 的換行是
\r\n,Linux/Unix 是\n??缙脚_(tái)建議使用System.lineSeparator()或BufferedWriter.newLine()。
性能與最佳實(shí)踐
- 使用緩沖:
BufferedInputStream/BufferedOutputStream/BufferedReader/BufferedWriter - 大塊讀寫:優(yōu)先
byte[]/char[]緩沖區(qū)讀寫,減少系統(tǒng)調(diào)用 - 明確編碼:文本讀寫顯式指定
Charset(如StandardCharsets.UTF_8) - 及時(shí)關(guān)閉:使用
try-with-resources自動(dòng)關(guān)閉(JDK 7+) - 追加寫入:輸出構(gòu)造器帶
append = true,如new FileOutputStream(path, true) - 避免小而頻繁的
read()/write():合并為批量操作
示例:拷貝任意文件(字節(jié)流 + 緩沖 + 大塊讀寫)
import java.io.*;
public class FileCopy {
public static void copyFile(String src, String dest) throws IOException {
try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(src));
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(dest))) {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}
}
public static void main(String[] args) throws IOException {
copyFile("D:/IO/source.bin", "D:/IO/target.bin");
}
}字符編碼與常見坑
FileReader/FileWriter使用“平臺(tái)默認(rèn)編碼”,在不同機(jī)器/IDE/系統(tǒng)下可能不同,易亂碼。- 推薦始終顯式使用編碼:
- 讀:
new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8) - 寫:
new OutputStreamWriter(new FileOutputStream(path), StandardCharsets.UTF_8)
- 讀:
- 文本文件中若包含表情/罕見字符,優(yōu)先
UTF-8(覆蓋更全)。
什么時(shí)候用字節(jié)流?什么時(shí)候用字符流?
- “只要涉及文本內(nèi)容且你需要‘字符’語義(如按行、按字符處理),用字符流”。
- “不確定是不是文本、或需要按原始字節(jié)處理(如復(fù)制圖片/壓縮包/視頻),用字節(jié)流”。
- “需要指定編碼(文本跨平臺(tái)),用 InputStreamReader/OutputStreamWriter 代替 FileReader/FileWriter”。
實(shí)戰(zhàn):綜合示例(讀取一個(gè) UTF-8 文本,轉(zhuǎn)換后寫入新文件)
import java.io.*;
import java.nio.charset.StandardCharsets;
public class TextTransformDemo {
public static void main(String[] args) {
String src = "D:/IO/input-utf8.txt";
String dest = "D:/IO/output-utf8.txt";
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(src), StandardCharsets.UTF_8));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dest), StandardCharsets.UTF_8))) {
String line;
int lineNo = 1;
while ((line = br.readLine()) != null) {
// 簡(jiǎn)單轉(zhuǎn)換:在每行前加上行號(hào)
bw.write(String.format("%04d: %s", lineNo++, line));
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}進(jìn)階一瞥:NIO 與 Files(了解即可)
java.nio.file.Files/Paths提供更現(xiàn)代的 API:Files.readAllLines(path, charset)讀所有行Files.write(path, bytes, options...)寫入字節(jié)Files.copy/Files.move/Files.delete文件操作
FileChannel、MappedByteBuffer可進(jìn)行高性能文件讀寫(大文件、零拷貝場(chǎng)景)。
常見錯(cuò)誤與改正
- 錯(cuò)誤:在
try外創(chuàng)建流,在finally中close()時(shí)忽略null判斷
修正:使用try-with-resources自動(dòng)關(guān)閉。 - 錯(cuò)誤:文本使用字節(jié)流讀取后直接
new String(bytes)未指定編碼
修正:顯式使用Charset;或改用字符流。 - 錯(cuò)誤:頻繁
read()/write()單字節(jié)
修正:使用緩沖流 + 批量讀寫。 - 錯(cuò)誤:路徑用
C:\\a\\b.txt忘記轉(zhuǎn)義
修正:改用正斜杠C:/a/b.txt或Paths.get("C:", "a", "b.txt")。
面試常見問題與答案
1)為什么有了字節(jié)流還需要字符流?
- 字節(jié)流面向原始數(shù)據(jù),不關(guān)心編碼;字符流關(guān)注“字符語義”,內(nèi)置解碼/編碼,更適合文本操作(按行、按字符)。
2)FileReader 與 InputStreamReader 區(qū)別?
FileReader是簡(jiǎn)化版字符輸入,使用平臺(tái)默認(rèn)編碼;InputStreamReader是“字節(jié)→字符”的橋接器,可顯式指定編碼,跨平臺(tái)更可靠,推薦。
3)BufferedReader.readLine() 為什么常用?
- 帶緩沖、按行讀取,避免頻繁系統(tǒng)調(diào)用,性能更好;并且直接得到“行”這個(gè)文本級(jí)別的語義單位。
4)hashCode/equals 和 IO 有關(guān)系嗎?
- 直接關(guān)系不大,但在使用
Set/Map統(tǒng)計(jì)文件名、緩存流對(duì)象時(shí)會(huì)涉及相等性與散列。IO 場(chǎng)景更多關(guān)注性能、正確編碼與資源釋放。
5)如何高效復(fù)制大文件?
- 使用
BufferedInputStream+BufferedOutputStream+ 大緩沖區(qū)(8KB~1MB),或使用 NIO 的Files.copy/FileChannel.transferTo/transferFrom。
6)什么時(shí)候需要 flush()?
- 對(duì)“帶緩沖”的輸出流/Writer,在你希望“立即”寫出數(shù)據(jù)時(shí)(如網(wǎng)絡(luò)/日志/交互式輸出),或程序即將結(jié)束但未關(guān)閉流時(shí)需要
flush()。
7)為什么 Windows 下是 \r\n 換行?
- 歷史原因;跨平臺(tái)代碼建議使用
System.lineSeparator()或BufferedWriter.newLine()來統(tǒng)一處理。
8)讀取二進(jìn)制文件時(shí)出現(xiàn)亂碼怎么辦?
- 不要把二進(jìn)制“按字符”解碼,直接按字節(jié)處理;只有在確定編碼并且是文本時(shí),才使用字符流或按正確編碼構(gòu)造字符串。
9)File 與 Files 的區(qū)別?
File是老 IO 的路徑抽象,Files是 NIO.2 的工具類,提供更豐富、更現(xiàn)代的文件操作 API。
10)try-with-resources 的底層原理?
- 編譯器語法糖:會(huì)在編譯期生成
try { ... } finally { resource.close(); }結(jié)構(gòu),并按“逆序”關(guān)閉多個(gè)資源。
小結(jié)
- 分清字節(jié)流與字符流,記住“文本=字符流,其他=字節(jié)流(拿不準(zhǔn)選字節(jié)流)”。
- 文本必須重視編碼,推薦
UTF-8,用InputStreamReader/OutputStreamWriter顯式指定。 - 性能優(yōu)化三件套:緩沖、批量讀寫、try-with-resources。
File只代表路徑,現(xiàn)代項(xiàng)目逐步擁抱 NIO.2(Paths/Files)。
到此這篇關(guān)于Java文件與IO流詳細(xì)攻略的文章就介紹到這了,更多相關(guān)Java文件與IO流內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Springboot和Jpa實(shí)現(xiàn)學(xué)生CRUD操作代碼實(shí)例
這篇文章主要介紹了Springboot和Jpa實(shí)現(xiàn)學(xué)生CRUD操作代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-03-03
Spring?Cloud微服務(wù)架構(gòu)Sentinel數(shù)據(jù)雙向同步
這篇文章主要為大家介紹了Spring?Cloud微服務(wù)架構(gòu)Sentinel數(shù)據(jù)雙向同步示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10
關(guān)于SpringMVC中控制器如何處理文件上傳的問題
這篇文章主要介紹了關(guān)于SpringMVC中控制器如何處理文件上傳的問題,在 Web 應(yīng)用程序中,文件上傳是一個(gè)常見的需求,例如用戶上傳頭像、上傳文檔等,本文將介紹 Spring MVC 中的控制器如何處理文件上傳,并提供示例代碼,需要的朋友可以參考下2023-07-07
SpringBoot3.0集成MybatisPlus的實(shí)現(xiàn)方法
本文主要介紹了SpringBoot3.0集成MybatisPlus的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-08-08
java POI解析Excel 之?dāng)?shù)據(jù)轉(zhuǎn)換公用方法(推薦)
下面小編就為大家?guī)硪黄猨ava POI解析Excel 之?dāng)?shù)據(jù)轉(zhuǎn)換公用方法(推薦)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-08-08
Java并發(fā)編程之ReentrantLock的實(shí)現(xiàn)示例
本文主要介紹了Java并發(fā)編程之ReentrantLock的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2026-02-02
Spring?Boot日志基礎(chǔ)使用之如何設(shè)置日志級(jí)別
這篇文章主要介紹了Spring?Boot日志基礎(chǔ)使用設(shè)置日志級(jí)別的方法,本文結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-09-09

