java.io 包详解
java.io
包是 Java 标准库中用于输入/输出(I/O)操作的核心包,提供了处理数据流、文件系统和序列化的各种类。这个包主要关注基于流的 I/O 操作。
核心类和接口
1. 字节流类(处理原始二进制数据)
-
InputStream(抽象类)
-
FileInputStream
:从文件读取字节 -
ByteArrayInputStream
:从字节数组读取 -
BufferedInputStream
:带缓冲的输入流 -
ObjectInputStream
:用于对象反序列化
-
-
OutputStream(抽象类)
-
FileOutputStream
:向文件写入字节 -
ByteArrayOutputStream
:向字节数组写入 -
BufferedOutputStream
:带缓冲的输出流 -
ObjectOutputStream
:用于对象序列化 -
PrintStream
:提供方便的打印方法(System.out 就是 PrintStream)
-
2. 字符流类(处理文本数据)
-
Reader(抽象类)
-
FileReader
:读取字符文件 -
BufferedReader
:带缓冲的字符读取(常用 readLine() 方法) -
InputStreamReader
:字节流到字符流的桥梁 -
StringReader
:从字符串读取
-
-
Writer(抽象类)
-
FileWriter
:写入字符文件 -
BufferedWriter
:带缓冲的字符写入 -
OutputStreamWriter
:字符流到字节流的桥梁 -
PrintWriter
:提供方便的打印方法 -
StringWriter
:写入到字符串
-
3. 文件系统类
-
File:表示文件和目录路径名的抽象表示
-
RandomAccessFile:支持随机访问文件
File file = new File("example.txt");
boolean exists = file.exists();
boolean isDir = file.isDirectory();RandomAccessFile raf = new RandomAccessFile("file.txt", "rw");
raf.seek(100); // 移动到第100个字节
常用操作
文件读写示例
字节流方式读取文件:
try (InputStream in = new FileInputStream("input.txt");BufferedInputStream bis = new BufferedInputStream(in)) {byte[] buffer = new byte[1024];int bytesRead;while ((bytesRead = bis.read(buffer)) != -1) {// 处理读取的数据}
} catch (IOException e) {e.printStackTrace();
}
字符流方式读取文件:
try (BufferedReader reader = new BufferedReader(new FileReader("input.txt"))) {String line;while ((line = reader.readLine()) != null) {System.out.println(line);}
} catch (IOException e) {e.printStackTrace();
}
写入文件:
try (BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"))) {writer.write("Hello, World!");writer.newLine();
} catch (IOException e) {e.printStackTrace();
}
对象序列化
序列化对象:
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("object.dat"))) {MyClass obj = new MyClass();oos.writeObject(obj);
} catch (IOException e) {e.printStackTrace();
}
反序列化对象:
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("object.dat"))) {MyClass obj = (MyClass) ois.readObject();
} catch (IOException | ClassNotFoundException e) {e.printStackTrace();
}
高级特性
1. 装饰器模式
Java I/O 使用了装饰器模式,可以灵活组合各种流:
// 组合了文件流、缓冲流和数据流
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("data.bin")));
2. 标准流
Java 提供了三个标准流:
-
System.in
(InputStream) -
System.out
(PrintStream) -
System.err
(PrintStream)
3. 文件过滤器
File dir = new File(".");
File[] txtFiles = dir.listFiles((d, name) -> name.endsWith(".txt"));
NIO 对比
虽然 java.io
包功能强大,但在 Java 1.4 引入的 java.nio
包(NIO)提供了更高效的 I/O 操作:
-
通道(Channel)和缓冲区(Buffer)代替流
-
非阻塞 I/O
-
文件锁定和内存映射文件
最佳实践
-
总是关闭资源:使用 try-with-resources 语句确保流被正确关闭
-
合理使用缓冲:对于频繁的小量 I/O 操作,使用缓冲流提高性能
-
选择正确的流类型:文本数据用字符流,二进制数据用字节流
-
处理异常:妥善处理 IOException
-
考虑编码:字符流注意指定正确的字符编码
总结
java.io
包提供了:
-
完整的 I/O 操作支持
-
流式数据处理模型
-
文件和目录操作能力
-
对象序列化机制
虽然在新代码中可以考虑使用 NIO,但 java.io
仍然是许多场景下的首选,特别是对于简单的文件操作和序列化需求。