序列化和反序列化(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 );
}
}
这个是反序列化。(()