标签:
序列化
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.WritableComparable;
public class TestWritableComparable {
public static void main(String[] agrs) throws Exception{
Student s = new Student("li",20,"man");
FileOutputStream fout = new FileOutputStream(
new File("/usr/local/test.txt"));
DataOutputStream out = new DataOutputStream(fout);
s.write(out);
fout.close();
out.close();
Student s1 = new Student();
FileInputStream fin = new FileInputStream(
new File("/usr/local/test.txt"));
DataInputStream in = new DataInputStream(fin);
s1.readFields(in);
System.out.println(s1.toString());
}
}
class Student implements WritableComparable<Student>{
private Text name = new Text();
private IntWritable age = new IntWritable();
private Text sex = new Text();
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
public Student() {
super();
}
public Student(String name, int age, String sex) {
super();
this.name = new Text(name);
this.age = new IntWritable(age);
this.sex = new Text(sex);
}
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 Text getSex() {
return sex;
}
public void setSex(Text sex) {
this.sex = sex;
}
@Override
public void readFields(DataInput in) throws IOException {
name.readFields(in);
age.readFields(in);
sex.readFields(in);
}
@Override
public void write(DataOutput out) throws IOException {
name.write(out);
age.write(out);
sex.write(out);
}
@Override
public int compareTo(Student o) {
int result = 0;
if((result = name.compareTo(o.getName())) != 0){
return result;
}
if((result = age.compareTo(o.getAge())) != 0){
return result;
}
if((result = sex.compareTo(o.getSex())) != 0){
return result;
}
return result;
}
}
标签:
原文地址:http://www.cnblogs.com/litaiqing/p/4846997.html