posts - 57,  comments - 33,  views - 1894

 

package cn.edu.sdut.acm;

import java.io.*;
import java.util.*;

class Student implements Serializable{ // 让Student对象可序列化
    String id;
    String name;
    String stuClass;
    int age;

    public Student(String id, String name, String stuClass, int age) {
        super();
        this.id = id;
        this.name = name;
        this.stuClass = stuClass;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + ", class=" + stuClass + "]";
    }
}

public class Main{
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Student stu1 = new Student("001", "Bob", "软件1805", 16); // 创建两个Student对象
        Student stu2 = new Student("002", "Join", "软件1804", 18);
        Student stuArray[] = new Student[2]; // 创建Student数组
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("\\javaDemo\\stu.dat")); // 创建输出流
        ObjectInputStream is = new ObjectInputStream(new FileInputStream("\\javaDemo\\stu.dat")); // 创建输入流
        stuArray[0] = stu1; // 对象放入数组
        stuArray[1] = stu2;
        os.writeObject(stuArray); // 将数组写入文件
        Object obj = is.readObject(); // 从文件中获取对象
        if (obj instanceof Student[]) { // 判断,并向上转型
            Student[] stus = (Student[]) obj;

            for (Student stu : stus) { // 迭代遍历输出
                System.out.println(stu);
            }
        }
        os.close(); // 关闭流
        is.close();
    }
}

 

posted on   fafrkvit  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示