15. I/O 系统
文件读写与流
File 类
import java.io.File;
File f = new File("/tmp/test.txt");
f.exists(); // 是否存在
f.isFile(); // 是否文件
f.isDirectory(); // 是否目录
f.length(); // 文件大小(字节)
f.getName(); // 文件名
f.getAbsolutePath(); // 绝对路径
f.delete(); // 删除
// 列目录
File dir = new File("/var/www/html");
String[] files = dir.list();
for (String name : files) System.out.println(name);
字节流(二进制)
读写图片、视频、任意二进制文件。
// 写文件
try (FileOutputStream fos = new FileOutputStream("test.dat")) {
fos.write(new byte[]{1, 2, 3, 4, 5});
}
// 读文件
try (FileInputStream fis = new FileInputStream("test.dat")) {
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1) {
// 处理 buf[0..len-1]
}
}
字符流(文本)
读写文本文件,自动处理编码。
// 写文本
try (PrintWriter pw = new PrintWriter("test.txt", "UTF-8")) {
pw.println("第一行");
pw.println("第二行");
}
// 读文本
try (BufferedReader br = new BufferedReader(
new InputStreamReader(new FileInputStream("test.txt"), "UTF-8"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
NIO 简介
Java NIO(New I/O)是非阻塞的,适合高并发服务器。核心概念:Channel、Buffer、Selector。
// 快速读整个文件(Java 7+)
List<String> lines = Files.readAllLines(
Paths.get("test.txt"), StandardCharsets.UTF_8);
// 快速写整个文件
Files.write(Paths.get("out.txt"),
"你好世界".getBytes(StandardCharsets.UTF_8));