欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 社会 > 序列化和反序列化(hadoop)

序列化和反序列化(hadoop)

2025/5/17 20:36:38 来源:https://blog.csdn.net/asdfghjj_/article/details/147915896  浏览:    关键词:序列化和反序列化(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 );
    }
}

 这个是反序列化。(()

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词