package com.qf.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
//对象要实现序列化接口
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student implements Serializable {
private Integer id;
private String name;
private String sex;
}
package com.qf.io;
import com.qf.pojo.Student;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
/**
* 将学生类写入磁盘
*/
public class WriterStudent {
public static void main(String[] args) throws IOException {
//准备数据
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(1001, "张三", "男"));
students.add(new Student(1002, "李四", "男"));
students.add(new Student(1003, "王五", "女"));
//在内存中创建了了 但是还没 在磁盘上写入
File file = new File("E:/2203/代码/frame/stuParent/stu/student.txt");
//获得目录结构信息
File parentFile = file.getParentFile();
System.out.println(parentFile);
//判断 如果目录不存在 就创建
if (!parentFile.exists()) {
//子夫目录一起创建
parentFile.mkdirs();
}
if (!file.exists()) {
//磁盘上创建文件
file.createNewFile();
}
//创建字节输出流
FileOutputStream fileOutputStream = new FileOutputStream(file);
//创建对象输出流
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
//写入
objectOutputStream.writeObject(students);
//关闭流
if (objectOutputStream != null) {
objectOutputStream.close();
fileOutputStream.close();
}
}
}
package com.qf.io;
import com.qf.pojo.Student;
import java.io.*;
import java.util.ArrayList;
//写入流 读 read
public class ReadStudent {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//读取文件
File file = new File("E:/2203/代码/frame/stuParent/stu/student.txt");
//创建字节输入流
FileInputStream fileInputStream = new FileInputStream(file);
//创建对象输入流
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
//读取文件
Object object = objectInputStream.readObject();
//类型转换
ArrayList<Student> students = (ArrayList<Student>) object;
//遍历
for (Student student : students) {
System.out.println("姓名:" + student.getName());
}
//关闭
if (objectInputStream != null) {
objectInputStream.close();
fileInputStream.close();
}
}
}
对象输入输出流
最新推荐文章于 2025-05-11 14:15:46 发布