Appearance
📁 文件与IO
IO 概述
Java IO(Input/Output)用于处理输入输出操作,包括文件读写、网络通信等。
IO 流类型
- 字节流:处理二进制数据(InputStream/OutputStream)
- 字符流:处理文本数据(Reader/Writer)
- 缓冲流:提高 IO 性能(BufferedInputStream/BufferedWriter)
- 对象流:序列化对象(ObjectInputStream/ObjectOutputStream)
File 类
文件操作
java
// 创建 File 对象
File file = new File("file.txt");
File dir = new File("directory");
// 检查文件和目录
boolean exists = file.exists();
boolean isFile = file.isFile();
boolean isDirectory = file.isDirectory();
// 创建文件和目录
boolean created = file.createNewFile(); // 创建文件
boolean dirCreated = dir.mkdir(); // 创建目录
boolean dirsCreated = dir.mkdirs(); // 创建多级目录
// 删除
boolean deleted = file.delete();
// 获取信息
String name = file.getName();
String path = file.getPath();
String absolutePath = file.getAbsolutePath();
long size = file.length();
long lastModified = file.lastModified();
// 列出目录内容
String[] files = dir.list();
File[] fileList = dir.listFiles();字节流
FileInputStream(文件输入流)
java
// 读取文件
FileInputStream fis = null;
try {
fis = new FileInputStream("file.txt");
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.out.println("读取失败: " + e.getMessage());
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
System.out.println("关闭失败: " + e.getMessage());
}
}
}
// 使用 try-with-resources
try (FileInputStream fis = new FileInputStream("file.txt")) {
int data;
while ((data = fis.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.out.println("读取失败: " + e.getMessage());
}FileOutputStream(文件输出流)
java
// 写入文件
try (FileOutputStream fos = new FileOutputStream("file.txt")) {
String content = "Hello World";
fos.write(content.getBytes());
} catch (IOException e) {
System.out.println("写入失败: " + e.getMessage());
}
// 追加模式
try (FileOutputStream fos = new FileOutputStream("file.txt", true)) {
String content = "\n追加内容";
fos.write(content.getBytes());
} catch (IOException e) {
System.out.println("追加失败: " + e.getMessage());
}字符流
FileReader(文件读取器)
java
// 读取文本文件
try (FileReader fr = new FileReader("file.txt")) {
int data;
while ((data = fr.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
System.out.println("读取失败: " + e.getMessage());
}FileWriter(文件写入器)
java
// 写入文本文件
try (FileWriter fw = new FileWriter("file.txt")) {
fw.write("Hello World");
} catch (IOException e) {
System.out.println("写入失败: " + e.getMessage());
}
// 追加模式
try (FileWriter fw = new FileWriter("file.txt", true)) {
fw.write("\n追加内容");
} catch (IOException e) {
System.out.println("追加失败: " + e.getMessage());
}缓冲流
BufferedReader(缓冲读取器)
java
// 使用缓冲读取
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("读取失败: " + e.getMessage());
}BufferedWriter(缓冲写入器)
java
// 使用缓冲写入
try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"))) {
bw.write("第一行");
bw.newLine(); // 换行
bw.write("第二行");
} catch (IOException e) {
System.out.println("写入失败: " + e.getMessage());
}对象流(序列化)
序列化对象
java
// 实现 Serializable 接口
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
// 构造方法、getter、setter...
}
// 序列化对象到文件
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("person.dat"))) {
Person person = new Person("张三", 25);
oos.writeObject(person);
} catch (IOException e) {
System.out.println("序列化失败: " + e.getMessage());
}反序列化对象
java
// 从文件反序列化对象
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream("person.dat"))) {
Person person = (Person) ois.readObject();
System.out.println("姓名: " + person.getName());
System.out.println("年龄: " + person.getAge());
} catch (IOException | ClassNotFoundException e) {
System.out.println("反序列化失败: " + e.getMessage());
}NIO(Java 7+)
Files 类
java
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
// 读取文件
Path path = Paths.get("file.txt");
try {
byte[] bytes = Files.readAllBytes(path);
String content = new String(bytes);
System.out.println(content);
// 读取所有行
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("读取失败: " + e.getMessage());
}
// 写入文件
try {
String content = "Hello World";
Files.write(path, content.getBytes());
// 写入多行
List<String> lines = Arrays.asList("第一行", "第二行");
Files.write(path, lines);
} catch (IOException e) {
System.out.println("写入失败: " + e.getMessage());
}
// 复制文件
try {
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println("复制失败: " + e.getMessage());
}
// 移动文件
try {
Path source = Paths.get("source.txt");
Path target = Paths.get("target.txt");
Files.move(source, target, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.out.println("移动失败: " + e.getMessage());
}
// 删除文件
try {
Files.delete(path);
} catch (IOException e) {
System.out.println("删除失败: " + e.getMessage());
}完整示例
java
public class IOExample {
// 读取文件
public static void readFile(String filename) {
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("读取失败: " + e.getMessage());
}
}
// 写入文件
public static void writeFile(String filename, String content) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(filename))) {
bw.write(content);
} catch (IOException e) {
System.out.println("写入失败: " + e.getMessage());
}
}
// 复制文件
public static void copyFile(String source, String target) {
try (FileInputStream fis = new FileInputStream(source);
FileOutputStream fos = new FileOutputStream(target)) {
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
fos.write(buffer, 0, length);
}
} catch (IOException e) {
System.out.println("复制失败: " + e.getMessage());
}
}
public static void main(String[] args) {
// 写入文件
writeFile("test.txt", "Hello World\n第二行");
// 读取文件
readFile("test.txt");
// 复制文件
copyFile("test.txt", "copy.txt");
}
}最佳实践
1. 使用 try-with-resources
java
// ✅ 好的做法:自动关闭资源
try (FileInputStream fis = new FileInputStream("file.txt")) {
// 使用资源
} catch (IOException e) {
// 处理异常
}2. 使用缓冲流提高性能
java
// ✅ 好的做法:使用缓冲流
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
// 读取文件
}
// ❌ 不好的做法:直接使用字符流(性能较差)
try (FileReader fr = new FileReader("file.txt")) {
// 读取文件
}3. 使用 NIO Files 类(Java 7+)
java
// ✅ 好的做法:使用 Files 类
Path path = Paths.get("file.txt");
List<String> lines = Files.readAllLines(path);下一步
掌握了文件与IO后,可以继续学习:
💡 提示:文件IO是程序开发的重要部分,选择合适的IO流可以提高程序性能
