导航菜单

Java 编程/文件与IO
课程进度 65% · 第7/10章7/10章 · 标签 1/2
1

字节流与字符流

Java 的 IO 体系分为字节流和字符流两大类。字节流处理二进制数据,字符流处理文本数据。

java
1
// 字符流(文本)
2
try (BufferedReader reader = new BufferedReader(
3
new FileReader("input.txt"))) {
4
String line;
5
while ((line = reader.readLine()) != null) {
6
System.out.println(line);
7
}
8
}
9
 
10
try (BufferedWriter writer = new BufferedWriter(
11
new FileWriter("output.txt"))) {
12
writer.write("Hello World");
13
writer.newLine();
14
}
15
 
16
// 字节流(二进制)
17
try (FileInputStream in = new FileInputStream("photo.jpg");
18
FileOutputStream out = new FileOutputStream("copy.jpg")) {
19
byte[] buffer = new byte[1024];
20
int len;
21
while ((len = in.read(buffer)) != -1) {
22
out.write(buffer, 0, len);
23
}
24
}
2

NIO 与 Files

java
1
import java.nio.file.*;
2
 
3
// Files 工具类(Java 7+)
4
String content = Files.readString(
5
Path.of("input.txt"));
6
System.out.println(content);
7
 
8
Files.writeString(
9
Path.of("output.txt"),
10
"Hello NIO",
11
StandardOpenOption.CREATE);
12
 
13
// 目录操作
14
Files.list(Path.of("."))
15
.forEach(System.out::println);
16
 
17
// 文件属性
18
System.out.println(Files.size(Path.of("file.txt")));
19
System.out.println(Files.getLastModifiedTime(Path.of("file.txt")));
20
 
21
// 复制/移动
22
Files.copy(Path.of("src.txt"), Path.of("dst.txt"),
23
StandardCopyOption.REPLACE_EXISTING);
24
Files.move(Path.of("old.txt"), Path.of("new.txt"));

📖NIO 的 Files 类简化了文件操作。优先使用 NIO 而非传统的 File 类