Java IO 流进阶:字符流与字节流的核心应用
Java IO 流涵盖字节流与字符流的区别,字节流处理所有文件类型,字符流处理文本。缓冲流通过内存缓存提升大文件读写性能。转换流用于指定编码解决乱码问题。JDK7 引入 try-with-resources 自动管理资源。实战案例展示了文件夹批量复制工具的实现,综合运用了嵌套流与递归遍历技巧。

Java IO 流涵盖字节流与字符流的区别,字节流处理所有文件类型,字符流处理文本。缓冲流通过内存缓存提升大文件读写性能。转换流用于指定编码解决乱码问题。JDK7 引入 try-with-resources 自动管理资源。实战案例展示了文件夹批量复制工具的实现,综合运用了嵌套流与递归遍历技巧。

字节流以 byte 为基本单位进行数据传输,它可以处理所有类型的文件,比如图片、视频、音频、文本等。 字符流以 char 为基本单位进行数据传输,它专门用于处理文本文件,底层会涉及字符编码的转换。
字节流的核心类是 InputStream 和 OutputStream,字符流的核心类是 Reader 和 Writer。 两者都是抽象类,实际开发中我们使用的是它们的子类,比如 FileInputStream、FileWriter 等。
核心结论:处理非文本文件用字节流,处理文本文件优先用字符流。
import java.io.FileInputStream;
import java.io.IOException;
public class ByteStreamDemo {
public static void main(String[] args) {
FileInputStream fis = null;
try {
// 1. 关联文件路径
fis = new FileInputStream("test.txt");
// 2. 定义缓冲区,大小为 1024 字节(1KB)
byte[] buffer = new byte[1024];
int len; // 记录每次读取的有效字节数
// 3. 循环读取数据
while ((len = fis.read(buffer)) != -1) {
// 将字节数组转换为字符串
System.out.print(new String(buffer, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4. 关闭流资源
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
注意事项:使用字节流读取文本文件时,如果文件编码是 UTF-8,而系统默认编码是 GBK,可能会出现乱码。这时候需要用字符流或者转换流来解决。
字符流的优势在于自动处理字符编码,默认使用系统编码,也可以手动指定编码格式。 下面是用 FileReader 和 FileWriter 实现文本文件的复制操作:
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CharStreamDemo {
public static void main(String[] args) {
FileReader fr = null;
FileWriter fw = null;
try {
// 1. 关联源文件和目标文件
fr = new FileReader("source.txt");
fw = new FileWriter("target.txt");
// 2. 定义字符缓冲区
char[] buffer = new char[1024];
int len;
// 3. 循环读写
while ((len = fr.read(buffer)) != -1) {
fw.write(buffer, 0, len);
// 刷新缓冲区,避免数据滞留
fw.flush();
}
System.out.println("✅ 文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 4. 关闭流资源,后开先关
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
核心结论:字符流读写文本文件时,无需手动处理编码转换,代码更简洁,且不易出现乱码。
没有缓冲的情况下,字节流和字符流的读写效率相近。 但在处理大文件时,两者都需要搭配缓冲流来提升性能。
缓冲流的原理是在内存中开辟一块缓冲区,一次性读取或写入大量数据,减少与磁盘的交互次数。 字节缓冲流的类是 BufferedInputStream 和 BufferedOutputStream。 字符缓冲流的类是 BufferedReader 和 BufferedWriter。
下面是缓冲流的性能测试案例:分别用普通字节流和缓冲字节流读取一个 100MB 的视频文件,记录耗时。
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class BufferedStreamTest {
public static void main(String[] args) {
long start = System.currentTimeMillis();
readWithBuffer("large_video.mp4");
long end = System.currentTimeMillis();
System.out.println("缓冲流耗时:" + (end - start) + "ms");
start = System.currentTimeMillis();
readWithoutBuffer("large_video.mp4");
end = System.currentTimeMillis();
System.out.println("普通流耗时:" + (end - start) + "ms");
}
// 使用缓冲字节流读取文件
private static void readWithBuffer(String path) {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(path))) {
byte[] buffer = new byte[1024];
while (bis.read(buffer) != -1) {
// 读取数据,不做输出
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 使用普通字节流读取文件
private static void readWithoutBuffer(String path) {
try (FileInputStream fis = new FileInputStream(path)) {
byte[] buffer = new byte[1024];
while (fis.read(buffer) != -1) {
// 读取数据,不做输出
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试结果(仅供参考):
缓冲流耗时:120ms 普通流耗时:850ms
核心结论:缓冲流能大幅提升 IO 操作效率,处理大文件时必须使用缓冲流。
转换流的作用是字节流和字符流之间的转换,它可以指定字符编码格式,解决文本文件读写的乱码问题。 转换流的核心类是 InputStreamReader 和 OutputStreamWriter。
当我们读取一个 UTF-8 编码的文件,而系统默认编码是 GBK 时,直接用 FileReader 会出现乱码。 此时可以用 InputStreamReader 指定编码格式为 UTF-8:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class ConvertStreamDemo {
public static void main(String[] args) {
try (InputStreamReader isr = new InputStreamReader(new FileInputStream("utf8_file.txt"), "UTF-8")) {
char[] buffer = new char[1024];
int len;
while ((len = isr.read(buffer)) != -1) {
System.out.print(new String(buffer, 0, len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项:指定的编码格式必须和文件的实际编码一致,否则仍然会出现乱码。 常见的编码格式有 UTF-8、GBK、GB2312、ISO-8859-1 等。
在 JDK7 之前,我们需要在 finally 块中手动关闭流资源,并且要判断流对象是否为 null,避免空指针异常。 这种写法比较繁琐,但兼容性最好。
JDK7 引入了 try-with-resources 语法,它可以自动关闭实现了 AutoCloseable 接口的资源,无需手动在 finally 块中关闭。 这种写法更简洁,代码可读性更高,是目前推荐的写法。
示例代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TryWithResourcesDemo {
public static void main(String[] args) {
// 将流对象声明在 try 的括号中,自动关闭
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
String line;
// 按行读取文本文件
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
核心结论:JDK7 及以上版本优先使用 try-with-resources 语法,简化资源释放代码。
实现一个工具类,能够复制指定文件夹下的所有文件和子文件夹,包括各种类型的文件(文本、图片、视频等)。 要求:
import java.io.*;
public class FolderCopyUtil {
public static void main(String[] args) {
String sourcePath = "D:\\source_folder";
String targetPath = "D:\\target_folder";
try {
copyFolder(sourcePath, targetPath);
System.out.println("✅ 文件夹复制成功!");
} catch (IOException e) {
System.out.println("❌ 文件夹复制失败:" + e.getMessage());
e.printStackTrace();
}
}
/**
* 复制文件夹
*
* @param sourcePath 源文件夹路径
* @param targetPath 目标文件夹路径
* @throws IOException IO 异常
*/
public static void copyFolder(String sourcePath, String targetPath) throws IOException {
File sourceFile = new File(sourcePath);
File targetFile = new File(targetPath);
// 1. 如果源文件不是文件夹,直接复制文件
if (!sourceFile.isDirectory()) {
copyFile(sourceFile, targetFile);
return;
}
// 2. 创建目标文件夹
if (!targetFile.exists()) {
boolean mkdirsSuccess = targetFile.mkdirs();
if (!mkdirsSuccess) {
throw new IOException("创建目标文件夹失败:" + targetPath);
}
}
// 3. 获取源文件夹下的所有文件和子文件夹
File[] files = sourceFile.listFiles();
if (files == null) {
return;
}
// 4. 循环复制每个文件和子文件夹
for (File file : files) {
String newSourcePath = file.getAbsolutePath();
String newTargetPath = targetPath + File.separator + file.getName();
copyFolder(newSourcePath, newTargetPath);
}
}
/**
* 复制单个文件
*
* @param sourceFile 源文件
* @param targetFile 目标文件
* @throws IOException IO 异常
*/
public static void copyFile(File sourceFile, File targetFile) throws IOException {
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile))) {
byte[] buffer = new byte[1024 * 8]; // 8KB 缓冲区
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
}
}
}
案例总结:这个工具类结合了字节流、缓冲流的核心知识,是实际开发中非常实用的功能。 通过这个案例,我们可以掌握 IO 流的嵌套使用和文件夹递归遍历的技巧。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
查找任何按下的键的javascript键代码、代码、位置和修饰符。 在线工具,Keycode 信息在线工具,online
JavaScript 字符串转义/反转义;Java 风格 \uXXXX(Native2Ascii)编码与解码。 在线工具,Escape 与 Native 编解码在线工具,online
使用 Prettier 在浏览器内格式化 JavaScript 或 HTML 片段。 在线工具,JavaScript / HTML 格式化在线工具,online
Terser 压缩、变量名混淆,或 javascript-obfuscator 高强度混淆(体积会增大)。 在线工具,JavaScript 压缩与混淆在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online