Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Hadoop learning-serialization and deserialization of person class objects-day07

Shulou Source: shulou.com Published: 2022-06-03 02:44:02 12月01日 Update

The code for the person class:

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 {

/ / equivalent to String type

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

/ / Serialization

Public void write (DataOutput out) throws IOException {

Name.write (out)

Age.write (out)

Male.write (out)

}

/ / deserialization

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)

}

}

The code for the test class:

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))

/ / Serialization

ByteArrayOutputStream baos = new ByteArrayOutputStream ()

DataOutputStream dataOut = new DataOutputStream (baos)

P.write (dataOut)

DataOut.close ()

/ / deserialization

Person newPerson = newPerson ()

NewPerson.readFields (new DataInputStream (new ByteArrayInputStream (baos.toByteArray ()

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

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

}

}

Tags: Sequence code type test object learning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Xiaomi Huawei OPPO Reno macOS