在计算机编程中,IO流(Input/Output Stream) 是实现程序与外部设备(如文件、网络、控制台)之间数据传输的核心机制。
核心概念:
Java 的 IO 操作主要位于 java.io 和 java.nio 包中。
分类方式 | 类型 | 说明 |
|---|---|---|
按流向 | 输入流 | InputStream, Reader |
输出流 | OutputStream, Writer | |
按数据单位 | 字节流 | 以字节为单位,处理任意类型数据 |
字符流 | 以字符为单位,专用于文本处理 |
✅ 选择建议:
InputStreamFileInputStream - 文件字节输入流// 传统方式(需手动关闭)
FileInputStream fis = null;
try {
fis = new FileInputStream("example.txt");
int content;
while ((content = fis.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}⚠️
read()返回int,-1 表示文件末尾。
OutputStreamFileOutputStream - 文件字节输出流FileOutputStream fos = null;
try {
fos = new FileOutputStream("output.txt");
String str = "Hello, World!";
byte[] bytes = str.getBytes("UTF-8"); // 推荐指定编码
fos.write(bytes);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}💡
write(byte[])可一次性写入整个字节数组,效率更高。
ReaderFileReader - 文件字符输入流FileReader fr = null;
try {
fr = new FileReader("example.txt");
int c;
while ((c = fr.read()) != -1) {
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}✅ 字符流自动处理编码转换,更适合文本读取。
WriterFileWriter - 文件字符输出流FileWriter fw = null;
try {
fw = new FileWriter("output.txt");
String str = "Hello, Character Stream!";
fw.write(str); // 直接写入字符串
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}直接使用基础流频繁读写磁盘效率低下。缓冲流通过在内存中设置缓冲区,减少IO操作次数。
BufferedInputStreamtry (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("example.txt"))) {
int content;
while ((content = bis.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}BufferedOutputStreamtry (BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("output.txt"))) {
String str = "Hello, Buffered Output Stream!";
bos.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}✅ 使用 try-with-resources 自动关闭资源,避免内存泄漏。
BufferedReader - 支持按行读取try (BufferedReader br = new BufferedReader(
new FileReader("example.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}🚀
readLine()是处理文本文件的利器!
BufferedWriter - 高效写入文本try (BufferedWriter bw = new BufferedWriter(
new FileWriter("output.txt"))) {
bw.write("Hello, Buffered Writer!");
bw.newLine(); // 跨平台换行
bw.write("Second Line");
} catch (IOException e) {
e.printStackTrace();
}💡
newLine()自动适配不同操作系统的换行符。
用于将 Java 对象保存到文件或通过网络传输。
ObjectOutputStreamclass Person implements Serializable {
private static final long serialVersionUID = 1L;
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}
}
// 写入对象
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("person.dat"))) {
Person person = new Person("Alice", 25);
oos.writeObject(person);
} catch (IOException e) {
e.printStackTrace();
}⚠️ 类必须实现
Serializable接口。
ObjectInputStreamtry (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("person.dat"))) {
Person person = (Person) ois.readObject();
System.out.println(person);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}🔐 注意安全风险:反序列化可能执行恶意代码。
File 类(传统IO)File file = new File("example.txt");
if (file.exists()) {
System.out.println("文件存在");
System.out.println("大小: " + file.length() + " bytes");
System.out.println("是否是文件: " + file.isFile());
System.out.println("是否是目录: " + file.isDirectory());
} else {
System.out.println("文件不存在");
}❌
File类功能有限,且部分方法已过时。
Files 类(NIO.2,推荐)Path path = Paths.get("example.txt");
// 读取所有行
try {
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
// 写入多行
List<String> content = Arrays.asList("Line 1", "Line 2");
try {
Files.write(Paths.get("output.txt"), content, StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}✅ 优势:
场景 | 推荐方案 |
|---|---|
文本文件读取 | BufferedReader 或 Files.readAllLines() |
文本文件写入 | BufferedWriter 或 Files.write() |
二进制文件处理 | BufferedInputStream / BufferedOutputStream |
对象持久化 | ObjectInputStream / ObjectOutputStream |
简单文件操作 | Files 工具类 |
Files 类 替代传统 File。Java IO 体系虽然复杂,但掌握以下核心即可应对大多数场景:
字节流 → 二进制数据
↓
字符流 → 文本数据
↓
缓冲流 → 提升性能
↓
对象流 → 序列化
↓
NIO.2 → 现代化高效操作理解这些组件的协作关系,你就能写出高效、健壮的文件处理代码!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。