对象输入输出流

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();
        }
    }


}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值