本文目录导读:

我将为您展示几个Java IO流的经典案例,涵盖文件读写、缓冲流、对象序列化等常用场景。
文件基础读写操作
import java.io.*;
public class FileBasicIO {
public static void main(String[] args) {
// 案例1: 使用FileInputStream和FileOutputStream复制文件
String sourcePath = "source.txt";
String destPath = "dest.txt";
try (FileInputStream fis = new FileInputStream(sourcePath);
FileOutputStream fos = new FileOutputStream(destPath)) {
int data;
byte[] buffer = new byte[1024];
while ((data = fis.read(buffer)) != -1) {
fos.write(buffer, 0, data);
}
System.out.println("文件复制完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
字符流读写文件
import java.io.*;
public class CharStreamExample {
public static void main(String[] args) {
// 使用FileReader和FileWriter进行字符流操作
try (FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt")) {
char[] buffer = new char[1024];
int length;
while ((length = reader.read(buffer)) != -1) {
writer.write(buffer, 0, length);
}
System.out.println("字符流写入完成");
} catch (IOException e) {
e.printStackTrace();
}
// 读取文本文件内容
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
缓冲流提高性能
import java.io.*;
public class BufferedStreamExample {
public static void main(String[] args) {
// 使用BufferedInputStream和BufferedOutputStream提高读写效率
try (BufferedInputStream bis = new BufferedInputStream(
new FileInputStream("large_file.zip"));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("large_file_copy.zip"))) {
byte[] buffer = new byte[8192]; // 8KB缓冲区
int bytesRead;
long startTime = System.currentTimeMillis();
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
long endTime = System.currentTimeMillis();
System.out.println("大文件复制完成,耗时:" + (endTime - startTime) + "ms");
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象序列化与反序列化
import java.io.*;
// 定义可序列化的对象
class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private transient String password; // transient字段不会被序列化
public Person(String name, int age, String password) {
this.name = name;
this.age = age;
this.password = password;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + ", password='" + password + "'}";
}
}
public class ObjectSerializationExample {
public static void main(String[] args) {
// 序列化对象到文件
Person person = new Person("张三", 25, "secret123");
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("person.dat"))) {
oos.writeObject(person);
System.out.println("对象序列化成功: " + person);
} catch (IOException e) {
e.printStackTrace();
}
// 从文件反序列化对象
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("person.dat"))) {
Person deserializedPerson = (Person) ois.readObject();
System.out.println("对象反序列化成功: " + deserializedPerson);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
递归遍历目录
import java.io.File;
public class DirectoryTraversal {
public static void main(String[] args) {
File directory = new File("C:/Users/Example/Desktop");
if (directory.exists() && directory.isDirectory()) {
listFilesRecursively(directory, 0);
}
}
public static void listFilesRecursively(File dir, int level) {
File[] files = dir.listFiles();
if (files == null) return;
StringBuilder indent = new StringBuilder();
for (int i = 0; i < level; i++) {
indent.append(" ");
}
for (File file : files) {
if (file.isDirectory()) {
System.out.println(indent + "📁 " + file.getName());
listFilesRecursively(file, level + 1);
} else {
System.out.println(indent + "📄 " + file.getName() +
" (" + file.length() + " bytes)");
}
}
}
}
合并多个文件
import java.io.*;
import java.util.Arrays;
import java.util.List;
public class FileMergeExample {
public static void main(String[] args) {
List<String> sourceFiles = Arrays.asList("part1.txt", "part2.txt", "part3.txt");
String outputFile = "merged.txt";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
for (String sourceFile : sourceFiles) {
try (BufferedReader reader = new BufferedReader(new FileReader(sourceFile))) {
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
System.out.println("已合并文件: " + sourceFile);
} catch (IOException e) {
System.err.println("读取文件失败: " + sourceFile);
}
}
System.out.println("所有文件合并完成!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
控制台输入输出
import java.io.*;
public class ConsoleIOExample {
public static void main(String[] args) {
// 使用BufferedReader读取控制台输入
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in))) {
System.out.print("请输入姓名: ");
String name = reader.readLine();
System.out.print("请输入年龄: ");
int age = Integer.parseInt(reader.readLine());
System.out.println("您输入的信息: 姓名=" + name + ", 年龄=" + age);
} catch (IOException e) {
e.printStackTrace();
}
// 使用Console类(在支持控制台的环境中使用)
Console console = System.console();
if (console != null) {
String username = console.readLine("用户名: ");
char[] password = console.readPassword("密码: ");
console.printf("登录成功!欢迎 %s%n", username);
}
}
}
文件属性操作
import java.io.File;
import java.io.IOException;
import java.nio.file.*;
public class FileAdvancedOperations {
public static void main(String[] args) {
// 使用NIO.2 API(Java 7+)
Path source = Paths.get("source.txt");
Path target = Paths.get("copy.txt");
try {
// 文件复制
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件复制完成");
// 文件移动
Path dest = Paths.get("moved.txt");
Files.move(target, dest, StandardCopyOption.REPLACE_EXISTING);
System.out.println("文件移动完成");
// 读取文件属性
BasicFileAttributes attrs = Files.readAttributes(dest, BasicFileAttributes.class);
System.out.println("创建时间: " + attrs.creationTime());
System.out.println("最后修改时间: " + attrs.lastModifiedTime());
System.out.println("文件大小: " + attrs.size() + " bytes");
// 删除文件
Files.delete(dest);
System.out.println("文件删除完成");
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行示例
public class IOExamples {
public static void main(String[] args) {
System.out.println("=== Java IO 流案例 ===");
System.out.println("1. 基础文件操作");
System.out.println("2. 字符流操作");
System.out.println("3. 缓冲流操作");
System.out.println("4. 对象序列化");
System.out.println("5. 目录遍历");
System.out.println("6. 文件合并");
System.out.println("7. 控制台输入输出");
System.out.println("8. 文件属性操作");
}
}
这些案例覆盖了Java IO流的主要使用场景:
- 字节流:处理二进制数据
- 字符流:处理文本数据
- 缓冲流:提高I/O性能
- 对象流:对象序列化与反序列化
- 文件操作:文件创建、读写、复制、删除等
- 目录操作:遍历、创建目录等
- 控制台I/O:键盘输入、屏幕输出
在实际开发中,根据需求选择合适的流类型至关重要,建议优先使用缓冲流来提高性能,使用try-with-resources自动管理资源。