The most simplified serialization saves Java objects

Source: Internet
Author: User
  1. Public class test1 {
  2. Final Static objectstreamclass DESC = objectstreamclass. lookupany (mybean. Class );
  3. Public static void main (string [] ARGs) throws ioexception, classnotfoundexception {
  4. File F = new file ("F: // F" + system. currenttimemillis () + ". Ser ");
  5. Fileoutputstream Fos = new fileoutputstream (f );
  6. Java. Io. objectoutputstream OOS = new myobjectoutputstream (FOS );
  7. Oos. writeobject (New mybean (byte) 1 ));
  8. Oos. writeobject (New mybean (byte) 2 ));
  9. Oos. Flush ();
  10. Oos. Close ();
  11. Fileinputstream FCM = new fileinputstream (f );
  12. Java. Io. objectinputstream OIS = new myobjectinputstream (FCM );
  13. System. Out. println (OIS. readobject ());
  14. System. Out. println (OIS. readobject ());
  15. Ois. Close ();
  16. }
  17. Static
  18. Class myobjectoutputstream extends objectoutputstream {
  19. Public myobjectoutputstream (outputstream out) throws ioexception {
  20. Super (out );
  21. }
  22. @ Override
  23. Protected void writestreamheader () throws ioexception {}
  24. @ Override
  25. Protected void writeclassdescriptor (objectstreamclass DESC) throws ioexception {}
  26. }
  27. Static
  28. Class myobjectinputstream extends objectinputstream {
  29. Public myobjectinputstream (inputstream in) throws ioexception {
  30. Super (in );
  31. }
  32. @ Override
  33. Protected void readstreamheader () throws ioexception, streamcompuptedexception {}
  34. @ Override
  35. Protected objectstreamclass readclassdescriptor () throws ioexception, classnotfoundexception {
  36. Return DESC;
  37. }
  38. }
  39. }
  40. Class mybean implements serializable {
  41. Private Static final long serialversionuid = 0l;
  42. Public mybean (byte ID ){
  43. This. I = ID;
  44. }
  45. Byte I = 0;
  46. @ Override
  47. Public String tostring (){
  48. Return this. getclass (). getname () + ":" + I;
  49. }
  50. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.