Java 中的输入输出(I/O)流主要分为字节流和字符流。这两类流为开发者提供了高效的文件读写方式,也解决了不同编码格式下的字符处理问题。本文将带你深入了解字节流和字符流的区别、应用场景以及如何使用它们处理文件操作。
字节流是以**字节(byte)**为单位操作数据的流。它用于处理所有类型的文件,包括文本文件、图片、视频等。字节流不关心数据的编码方式,直接传输文件的原始字节。
Java 中提供了字节流的两个顶层抽象类:
字节流的常见实现类:
示例:用字节流复制一个文件
以下代码展示了如何使用字节流读取一个文件并将其写入另一个文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class ByteStreamExample { public static void main(String[] args) { String sourceFile = "source.txt"; // 源文件路径 String destinationFile = "destination.txt"; // 目标文件路径 try (FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destinationFile)) { byte[] buffer = new byte[1024]; // 每次读取1KB的数据 int bytesRead; while ((bytesRead = fis.read(buffer)) != -1) { fos.write(buffer, 0, bytesRead); } System.out.println("文件复制成功!"); } catch (IOException e) { e.printStackTrace(); } } } |
关键点:
字符流是以**字符(char)**为单位操作数据的流,专为处理文本文件而设计。它会自动根据编码格式将字节转换为字符或将字符转换为字节。
Java 中提供了字符流的两个顶层抽象类:
字符流的常见实现类:
示例:用字符流读写文本文件
以下代码展示了如何使用字符流读取一个文本文件并将其内容写入另一个文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class CharStreamExample { public static void main(String[] args) { String sourceFile = "source.txt"; // 源文件路径 String destinationFile = "destination.txt"; // 目标文件路径 try (FileReader fr = new FileReader(sourceFile); FileWriter fw = new FileWriter(destinationFile)) { char[] buffer = new char[1024]; // 每次读取1KB的字符 int charsRead; while ((charsRead = fr.read(buffer)) != -1) { fw.write(buffer, 0, charsRead); } System.out.println("文件复制成功!"); } catch (IOException e) { e.printStackTrace(); } } } |
关键点:
特性 | 字节流 | 字符流 |
---|---|---|
数据单位 | 字节(byte) | 字符(char) |
操作对象 | 所有文件类型 | 仅限文本文件 |
编码处理 | 不处理编码,直接传输 | 自动处理编码 |
常见类 | InputStream, OutputStream | Reader, Writer |
选择依据:
使用 BufferedReader 按行读取文本
BufferedReader 提供了 readLine() 方法,可以按行读取文本文件:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class BufferedReaderExample { public static void main(String[] args) { String filePath = "source.txt"; try (BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } |
优点:
使用 BufferedWriter 写入文本
BufferedWriter 提供了 newLine() 方法,可以快速写入多行文本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class BufferedWriterExample { public static void main(String[] args) { String filePath = "output.txt"; try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) { bw.write("这是第一行内容"); bw.newLine(); bw.write("这是第二行内容"); System.out.println("内容写入成功!"); } catch (IOException e) { e.printStackTrace(); } } } |