PageRenderTime 70ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/hadoop-practice/src/main/java/com/doctor/hadoop/common/classes/WritablePractice.java

https://gitlab.com/doctorwho1986/doctor
Java | 86 lines | 61 code | 19 blank | 6 comment | 0 complexity | bba28ac8e322af325f53064bf359e4f1 MD5 | raw file
  1. package com.doctor.hadoop.common.classes;
  2. import java.io.DataInput;
  3. import java.io.DataOutput;
  4. import java.io.IOException;
  5. import java.time.LocalDate;
  6. import org.apache.hadoop.io.DataInputBuffer;
  7. import org.apache.hadoop.io.DataOutputBuffer;
  8. import org.apache.hadoop.io.Writable;
  9. import com.alibaba.fastjson.JSON;
  10. import com.google.common.base.Preconditions;
  11. /**
  12. * hadoop序列化
  13. * @author doctor
  14. *
  15. * @since 2015年1月22日 上午12:55:42
  16. */
  17. public class WritablePractice {
  18. public static void main(String[] args) throws IOException {
  19. Person person = new Person();
  20. person.setName("doctor");
  21. person.setBirth(LocalDate.now().minusYears(1000));
  22. System.out.println(person);
  23. DataOutputBuffer out = new DataOutputBuffer();
  24. person.write(out);
  25. DataInputBuffer in = new DataInputBuffer();
  26. in.reset(out.getData(), out.getLength());
  27. Person person2 = Person.read(in);
  28. System.out.println(person2);
  29. Preconditions.checkState(person.toString().equals(person2.toString()));
  30. }
  31. private static class Person implements Writable {
  32. private String name;
  33. private LocalDate birth;
  34. public String getName() {
  35. return name;
  36. }
  37. public void setName(String name) {
  38. this.name = name;
  39. }
  40. public LocalDate getBirth() {
  41. return birth;
  42. }
  43. public void setBirth(LocalDate birth) {
  44. this.birth = birth;
  45. }
  46. @Override
  47. public void write(DataOutput out) throws IOException {
  48. out.writeUTF(name);
  49. out.writeUTF(birth.toString());
  50. }
  51. @Override
  52. public void readFields(DataInput in) throws IOException {
  53. name = in.readUTF();
  54. String temp = in.readUTF();
  55. this.birth = LocalDate.parse(temp);
  56. }
  57. public static Person read(DataInput in)throws IOException{
  58. Person person = new Person();
  59. person.readFields(in);
  60. return person;
  61. }
  62. @Override
  63. public String toString() {
  64. return JSON.toJSONString(this);
  65. }
  66. }
  67. }