Java 输入输出(I/O)详解与常用代码大全
Java 的输入输出(I/O)主要通过 java.io 和 java.nio 包实现,用于读取文件、键盘输入、网络数据等,以及写入文件、控制台输出等。下面按场景分类,汇总最实用、最常用的代码示例(基于 Java 8+,推荐使用 try-with-resources 自动关闭资源)。
1. 控制台输入(键盘输入)
最常用:Scanner(推荐新手)
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
// 读取一行字符串
System.out.print("请输入姓名:");
String name = sc.nextLine();
// 读取整数
System.out.print("请输入年龄:");
int age = sc.nextInt();
// 读取浮点数
double score = sc.nextDouble();
// 关闭(可选,System.in 不建议关闭)
sc.close();
高级:BufferedReader(性能更好,读取大输入)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入内容:");
String line = br.readLine(); // 读取一行
2. 控制台输出
System.out.println("普通输出,自动换行");
System.out.print("不换行输出");
System.out.printf("格式化输出:年龄 %d,成绩 %.2f\n", age, score);
3. 文件读取(最常用方式)
方式一:Files + Paths(Java 7+,最简洁)
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.List;
try {
// 读取整个文件为字符串
String content = Files.readString(Paths.get("file.txt"));
// 读取所有行到 List
List<String> lines = Files.readAllLines(Paths.get("file.txt"));
// 逐行读取(推荐大文件)
Files.lines(Paths.get("file.txt")).forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
方式二:BufferedReader(经典,高效)
import java.io.*;
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
4. 文件写入
方式一:Files(最简洁)
import java.nio.file.*;
try {
// 写入字符串(覆盖)
Files.writeString(Paths.get("output.txt"), "Hello Java");
// 追加写入多行
Files.write(Paths.get("output.txt"),
List.of("第一行", "第二行"),
StandardOpenOption.APPEND, StandardOpenOption.CREATE);
} catch (IOException e) {
e.printStackTrace();
}
方式二:BufferedWriter(经典)
try (BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt", true))) { // true 为追加
bw.write("这是写入的内容");
bw.newLine(); // 换行
bw.write("第二行");
} catch (IOException e) {
e.printStackTrace();
}
5. 复制文件(实用工具方法)
try {
Files.copy(Paths.get("source.txt"), Paths.get("target.txt"),
StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
6. 序列化对象(保存对象到文件)
// 对象需实现 Serializable 接口
class Person implements java.io.Serializable {
String name;
int age;
// transient 字段不序列化(如密码)
transient String password;
}
// 序列化(保存对象)
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.obj"))) {
oos.writeObject(new Person("张三", 25));
}
// 反序列化(读取对象)
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.obj"))) {
Person p = (Person) ois.readObject();
System.out.println(p.name);
}
7. 常用路径操作(java.nio.file)
Path path = Paths.get("dir/sub/file.txt");
// 获取文件名、父目录、扩展名
String fileName = path.getFileName().toString(); // file.txt
String parent = path.getParent().toString(); // dir/sub
String ext = fileName.substring(fileName.lastIndexOf(".") + 1); // txt
// 创建目录
Files.createDirectories(Paths.get("new/dir"));
// 判断文件是否存在
if (Files.exists(path)) { ... }
// 删除文件/目录
Files.deleteIfExists(path);
总结对比表(推荐选择)
| 场景 | 推荐方式 | 原因 |
|---|---|---|
| 简单控制台输入 | Scanner | 易用、支持多种类型 |
| 大量文本读取 | BufferedReader / Files.lines | 高效、内存友好 |
| 小文件读写 | Files.readString/writeString | 代码最少 |
| 大文件读写 | BufferedReader/Writer | 性能好 |
| 复制/移动/删除文件 | Files.copy/move/delete | 简洁原子操作 |
| 保存对象状态 | ObjectOutputStream | 序列化 |
注意事项
- 始终使用 try-with-resources 自动关闭资源,避免资源泄露。
- 处理 IOException(文件不存在、权限问题等)。
- 路径使用
Paths.get(),跨平台兼容(Windows/Linux)。 - 大文件避免一次性读入内存。
这些代码覆盖了 Java I/O 的 95% 日常需求,直接复制即可使用。如果需要网络 I/O(如 Socket)、JSON 文件读写、CSV 处理等高级用法,欢迎继续提问!