第五章:输入输出(IO)
5.2 字节流与字符流
5.2.1 字节流(Byte Streams)
字节流是Java IO中最基础的流类型,用于处理二进制数据(如图片、音频、视频等)或原始字节数据。
核心类:
InputStream:所有字节输入流的抽象父类- 常用子类:
FileInputStream、ByteArrayInputStream
- 常用子类:
OutputStream:所有字节输出流的抽象父类- 常用子类:
FileOutputStream、ByteArrayOutputStream
- 常用子类:
示例代码:文件复制(字节流)
try (InputStream in = new FileInputStream("source.txt");
OutputStream out = new FileOutputStream("target.txt")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
5.2.2 字符流(Character Streams)
字符流专门处理文本数据(如.txt、.csv文件),基于Unicode编码自动处理字符转换。
核心类:
Reader:所有字符输入流的抽象父类- 常用子类:
FileReader、InputStreamReader
- 常用子类:
Writer:所有字符输出流的抽象父类- 常用子类:
FileWriter、OutputStreamWriter
- 常用子类:
示例代码:读取文本文件(字符流)
try (Reader reader = new FileReader("text.txt")) {
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, charsRead));
}
} catch (IOException e) {
e.printStackTrace();
}
5.2.3 字节流与字符流的区别
| 特性 | 字节流 | 字符流 |
|---|---|---|
| 数据单位 | 字节(8-bit) | 字符(16-bit Unicode) |
| 适用场景 | 二进制文件(如图片) | 文本文件(如日志) |
| 是否处理编码 | 不处理字符编码转换 | 自动处理编码(如UTF-8) |
| 性能 | 更高(无编码转换开销) | 稍低(需编码转换) |
5.2.4 转换流(Bridge Streams)
通过InputStreamReader和OutputStreamWriter实现字节流与字符流的桥接:
// 将字节流转换为字符流(指定UTF-8编码)
try (Reader reader = new InputStreamReader(
new FileInputStream("data.txt"), StandardCharsets.UTF_8)) {
// 使用字符流操作...
}
5.2.5 缓冲流(Buffered Streams)
通过缓冲机制提升IO性能:
BufferedInputStream/BufferedOutputStream(字节缓冲)BufferedReader/BufferedWriter(字符缓冲)
示例:高效读取文本行
try (BufferedReader br = new BufferedReader(new FileReader("large.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
最佳实践:
- 优先使用字符流处理文本,避免手动处理编码问题。
- 对大文件操作时,务必使用缓冲流减少磁盘IO次数。
