温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Hadoop学习--person类对象的序列化和反序列化--day07

发布时间:2020-08-02 00:44:06 来源:网络 阅读:841 作者:zhicx 栏目:大数据

person类的代码:

import java.io.DataInput;

import java.io.DataOutput;

import java.io.IOException;


import org.apache.hadoop.io.BooleanWritable;

import org.apache.hadoop.io.IntWritable;

import org.apache.hadoop.io.Text;

import org.apache.hadoop.io.Writable;


public class Person implements Writable {

//相当于String类型

private Text name;

public Text getName() {

return name;

}

public void setName(Text name) {

this.name = name;

}

public IntWritable getAge() {

return age;

}

public void setAge(IntWritable age) {

this.age = age;

}

public BooleanWritable getMale() {

return male;

}

public void setMale(BooleanWritable male) {

this.male = male;

}

private IntWritable age;

private BooleanWritable male;

//序列化

public void write(DataOutput out) throws IOException{

name.write(out);

age.write(out);

male.write(out);

}

//反序列化

public void readFields(DataInput in) throws IOException{

name = new Text();

age=new IntWritable();

male=new BooleanWritable();

name.readFields(in);

age.readFields(in);

male.readFields(in);

}

}

测试类的代码:

import java.io.ByteArrayInputStream;

import java.io.ByteArrayOutputStream;

import java.io.DataInputStream;

import java.io.DataOutputStream;


import org.apache.hadoop.io.BooleanWritable;

import org.apache.hadoop.io.IntWritable;

import org.apache.hadoop.io.Text;

import org.junit.Test;


public class TestPerson {

  @Test

  public void testSeria() throws Exception{

 //new person

 Person p = new Person();

 p.setName(new Text("tomas"));

 p.setAge(new IntWritable(12));

 p.setMale(new BooleanWritable(false));

 //序列化

 ByteArrayOutputStream baos = new ByteArrayOutputStream();

 DataOutputStream dataOut = new DataOutputStream(baos);

 p.write(dataOut);

 dataOut.close();

 //反序列化

 Person newPerson = new Person();

 newPerson.readFields(new DataInputStream(new ByteArrayInputStream(baos.toByteArray())));

 System.out.println(newPerson.getName());

 System.out.println(newPerson.getAge().get());

 

 

  }

}


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI