序列化和反序列化(hadoop)

1.先将上一个博客的Student复制粘贴后面加上H

在StudentH中敲下面代码

package com.example.sei;
import org.apache.hadoop.io.Writable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
//学生类,姓名,年龄
//支持hadoop序列化
//1.要实现Writable接口
//2.补充一个空参构造
public class StudentH implements Writable {
   String name;
   int age;

   //空参构造
   public StudentH() {}
    public StudentH(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();
    }
}

2.然后将TestStudent复制粘贴后面加上H

在TestStudentH中敲下面代码

package com.example.sei;
 
import java.io.*;
 
public class TestStudentH {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        StudentH student = new StudentH("John", 20);
        System.out.println(student.name + "  " + student.age );
 
        //hadoop序列化:把对象保存到一个文件中
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("student_hadoop.ser"));
      student.write(dos);
 
    }
}
这个是序列化

package com.example.sei;
 
import java.io.*;
 
public class TestStudentH {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
//        StudentH student = new StudentH("John", 20);
//        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"));
        StudentH student1 = new StudentH();
        student1.readFields(dis);
        System.out.println(student1.name + "  " + student1.age );
    }
}

 这个是反序列化。(()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值