java小任务03

发布于:2025-05-15 ⋅ 阅读:(84) ⋅ 点赞:(0)
public class Student implements Serializable {
    String name;
    int age;
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class Student_HADOOP implements Writable {
    String name;
    int age;
    // 空参构造
    public Student_HADOOP() {

    }
    public Student_HADOOP(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // write: 在序列化的时候,调用。把对象写到文件
    @Override
    public void write(DataOutput dataOutput) throws IOException {
        //dataOutput.write(字段)
        dataOutput.writeUTF(name);
        dataOutput.writeInt(age);
    }

    // readFields: 在反序列化的时候,调用。从文件中读出内容,还原这个对象
    // 字段的顺序要与write中的顺序一致
    @Override
    public void readFields(DataInput dataInput) throws IOException {
        // 字段 = dataInput.read();
        name = dataInput.readUTF();
        age = dataInput.readInt();
    }
}

public class TestStudent {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        /*Student student = new Student("张三", 18);
        System.out.println(student.name + " " + student.age);


        // java序列化: 把对象保存到一个文件中
        // 1. 让这个类实现Serializable接口
        // 2. 创建一个输出流
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("stdent_java.ser"));
        // 3. 把对象写入到文件中
        oos.writeObject(student);
        // 4. 关闭
        oos.close();*/
        // java反序列化: 从文件student_java.ser中读出内容,还原这个对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("stdent_java.ser"));
        Student student = (Student) ois.readObject();
        System.out.println(student.name + " " + student.age);
    }
}

public class TestStudentHADOOP {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        // 实例化student对象
        Student_HADOOP student = new Student_HADOOP("张三", 18);
        System.out.println(student.name + " " + student.age);

        // hadoop序列化:把对象保存到一个文件中
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("student_hadoop.ser"));
        student.write(dos);

        // hadoop反序列化:从文件中读取对象
        DataInputStream dis = new DataInputStream(new FileInputStream("student_hadoop.ser"));
        Student_HADOOP student1 = new Student_HADOOP();
        student1.readFields(dis);
        System.out.println(student1.name + " " + student1.age);
    }
}

网站公告

今日签到

点亮在社区的每一天
去签到