本文目录导读:

我将为你详细介绍Java中IO流的使用方法,并通过实际案例来演示。
IO流基础概念
Java IO流分为两大类:
- 字节流:处理二进制数据(图片、视频等)
- 字符流:处理文本数据
常用IO流案例
文件复制(字节流)
import java.io.*;
public class FileCopyDemo {
public static void main(String[] args) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// 创建输入流和输出流
fis = new FileInputStream("source.jpg");
fos = new FileOutputStream("target.jpg");
// 缓冲区
byte[] buffer = new byte[1024];
int len;
// 读取并写入
while ((len = fis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("文件复制完成!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流
try {
if (fis != null) fis.close();
if (fos != null) fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文本文件读写(字符流)
import java.io.*;
public class TextFileReadWriteDemo {
public static void main(String[] args) {
// 写入文件
writeTextFile("example.txt");
// 读取文件
readTextFile("example.txt");
}
// 写入文本文件
public static void writeTextFile(String fileName) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(fileName))) {
bw.write("Hello, World!");
bw.newLine();
bw.write("这是第二行内容");
bw.newLine();
bw.write("Java IO流操作示例");
System.out.println("文件写入成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
// 读取文本文件
public static void readTextFile(String fileName) {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
对象序列化(对象流)
import java.io.*;
// 必须实现Serializable接口
class Student implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private int age;
private transient String password; // transient字段不会被序列化
public Student(String name, int age, String password) {
this.name = name;
this.age = age;
this.password = password;
}
@Override
public String toString() {
return "Student{name='" + name + "', age=" + age + ", password='" + password + "'}";
}
}
public class ObjectStreamDemo {
public static void main(String[] args) {
String filePath = "student.dat";
// 序列化:将对象写入文件
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(filePath))) {
Student student = new Student("张三", 20, "secret123");
oos.writeObject(student);
System.out.println("对象序列化成功!");
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化:从文件读取对象
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(filePath))) {
Student student = (Student) ois.readObject();
System.out.println("反序列化后的对象:" + student);
// 注意:password字段为null,因为是transient修饰
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
数据流读写(DataStream)
import java.io.*;
public class DataStreamDemo {
public static void main(String[] args) {
String filePath = "data.txt";
// 写入各种类型的数据
try (DataOutputStream dos = new DataOutputStream(
new FileOutputStream(filePath))) {
dos.writeInt(100);
dos.writeDouble(99.99);
dos.writeBoolean(true);
dos.writeUTF("Hello DataStream");
System.out.println("数据写入成功!");
} catch (IOException e) {
e.printStackTrace();
}
// 读取数据(必须按照写入顺序读取)
try (DataInputStream dis = new DataInputStream(
new FileInputStream(filePath))) {
int intValue = dis.readInt();
double doubleValue = dis.readDouble();
boolean boolValue = dis.readBoolean();
String strValue = dis.readUTF();
System.out.println("读取的数据:");
System.out.println("int: " + intValue);
System.out.println("double: " + doubleValue);
System.out.println("boolean: " + boolValue);
System.out.println("string: " + strValue);
} catch (IOException e) {
e.printStackTrace();
}
}
}
文件和目录操作(File类)
import java.io.*;
public class FileOperationDemo {
public static void main(String[] args) {
// 创建目录
File dir = new File("testDir");
if (!dir.exists()) {
dir.mkdir();
System.out.println("目录创建成功");
}
// 创建文件
File file = new File(dir, "test.txt");
try {
if (file.createNewFile()) {
System.out.println("文件创建成功:" + file.getAbsolutePath());
}
} catch (IOException e) {
e.printStackTrace();
}
// 获取文件信息
System.out.println("文件名:" + file.getName());
System.out.println("文件大小:" + file.length() + " bytes");
System.out.println("最后修改时间:" + file.lastModified());
System.out.println("是否可读:" + file.canRead());
System.out.println("是否可写:" + file.canWrite());
// 列出目录内容
File[] files = dir.listFiles();
if (files != null) {
for (File f : files) {
System.out.println(f.getName() + " - " +
(f.isFile() ? "文件" : "目录"));
}
}
// 删除文件
if (file.delete()) {
System.out.println("文件删除成功");
}
// 删除目录
if (dir.delete()) {
System.out.println("目录删除成功");
}
}
}
实用工具类
简化流操作的工具类
import java.io.*;
import java.nio.file.*;
public class IOUtils {
// 复制文件(Java 7+ NIO方式)
public static void copyFile(String sourcePath, String targetPath)
throws IOException {
Files.copy(Paths.get(sourcePath), Paths.get(targetPath),
StandardCopyOption.REPLACE_EXISTING);
}
// 读取文件内容为字符串
public static String readFileToString(String filePath) throws IOException {
return new String(Files.readAllBytes(Paths.get(filePath)));
}
// 写入字符串到文件
public static void writeStringToFile(String filePath, String content)
throws IOException {
Files.write(Paths.get(filePath), content.getBytes());
}
// 读取文件所有行
public static void readAllLines(String filePath) throws IOException {
Files.lines(Paths.get(filePath)).forEach(System.out::println);
}
}
使用try-with-resources自动关闭资源
import java.io.*;
public class TryWithResourcesDemo {
public static void main(String[] args) {
String content = "使用try-with-resources自动管理资源";
// 自动关闭资源
try (FileWriter fw = new FileWriter("autoClose.txt");
BufferedWriter bw = new BufferedWriter(fw)) {
bw.write(content);
System.out.println("写入成功,资源自动关闭");
} catch (IOException e) {
e.printStackTrace();
}
// 读取文件
try (FileReader fr = new FileReader("autoClose.txt");
BufferedReader br = new BufferedReader(fr)) {
System.out.println("读取内容:" + br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
最佳实践建议
-
选择合适的流类型
- 处理二进制文件使用字节流
- 处理文本文件使用字符流
- 需要高效读写使用缓冲流
-
资源管理
- 使用try-with-resources自动关闭资源
- 在finally块中关闭资源(旧版Java)
-
异常处理
- 处理IOException异常
- 不要忽略异常
- 根据需要进行异常处理或抛出
-
性能优化
- 使用缓冲区提高效率
- 合理设置缓冲区大小(通常8KB-64KB)
-
编码问题
- 指定正确的字符编码(如UTF-8)
- 使用InputStreamReader/OutputStreamWriter转换编码
这些案例涵盖了Java IO流的主要使用场景,你可以根据实际需求选择合适的实现方式。