Using XStream is the implementation of XML and Java Object Conversion (6)--persistence

Source: Internet
Author: User
Tags addall object serialization serialization

Nine, The persistence of

In the example in section eighth, when we manipulate a set of objects, we can specify writer, outputstream to write out the serialized XML data, and we can also specify reader, InputStream to read the serialized XML data. We need to specify the input and output stream when we need to write and read the file, and we need to explicitly call the input and output method to implement the serialization and deserialization of the Java object, in fact, we can make the Java object serialization and deserialization operation Implicit, automatic Done, that's what we're going to learn: Persistencestrategy, Xmlarraylist, XmlMap and Xmlset.

Persistencestrategy is our persistence strategy, which defines our storage and reading protocols, and is the actual tool for storing and reading XML. The persistence strategy provided by the XStream framework is only filepersistencestrategy this one, persisting XML data to the file system, but we can define our own persistence policies (such as persisting into the database), Just inherit the Persistencestrategy interface.

Xmlarraylist, XmlMap, and Xmlset are 3 of our familiar collection tool classes that let us manipulate Java objects in a way we are very familiar with, and implicitly store and read the XML we need.

Here we take xmlarraylist as an example to learn.

1, Simple storage

The procedure is as follows:

Java code
  1. Package CN.TJPU.ZHW.XML.XSTREAM6;
  2. Import Java.io.File;
  3. Import java.util.List;
  4. Import Com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
  5. Import Com.thoughtworks.xstream.persistence.PersistenceStrategy;
  6. Import com.thoughtworks.xstream.persistence.XmlArrayList;
  7. public class Persistencemain {
  8. public static void Main (string[] args) {
  9. Create persistence policies (define storage tools and storage locations)
  10. Note: D:/tmp is an existing directory, otherwise it will error
  11. Persistencestrategy strategy = new Filepersistencestrategy (
  12. New File ("d:/tmp"));
  13. Create an Action tool
  14. List List = new Xmlarraylist (strategy);
  15. System.out.println ("list.size () =" +list.size () when the Xmlarraylist object was created);
  16. Add data
  17. List.add (New person ("Zhang San"));
  18. List.add (New person ("John Doe"));
  19. List.add (New person ("fluffy"));
  20. List.add (New person ("Big Bear"));
  21. System.out.println ("After adding 4 elements list.size () =" +list.size ());
  22. Delete "John Doe"
  23. List.remove (1);
  24. System.out.println ("Removed 1 elements after list.size () =" +list.size ());
  25. }
  26. }
  27. Class Person {
  28. Public person (String name) {
  29. THIS.name = name;
  30. }
  31. private String name;
  32. Public String GetName () {
  33. return name;
  34. }
  35. public void SetName (String name) {
  36. THIS.name = name;
  37. }
  38. Public String toString () {
  39. Return "name= of the Person object" + getName ();
  40. }
  41. }

Operation Result:

Java code
    1. List.size () =0 when the Xmlarraylist object was first created
    2. After adding 4 elements list.size () =4
    3. After removing 1 elements list.size () =3

Now we look at the D:/tmp directory and we will find 3 files [email protected], [email protected] and [email protected]. These 3 files are the 3 person objects we store, and their contents are:

[Email protected] File:

XML code
    1. <cn.tjpu.zhw.xml.xstream6.Person>
    2. <name> Zhang San </name>
    3. </cn.tjpu.zhw.xml.xstream6.Person>

[Email protected] File

XML code
    1. <cn.tjpu.zhw.xml.xstream6.Person>
    2. <name> Fluffy </name>
    3. </cn.tjpu.zhw.xml.xstream6.Person>

[Email protected] File:

XML code
    1. <cn.tjpu.zhw.xml.xstream6.Person>
    2. <name> Big Bear </name>
    3. </cn.tjpu.zhw.xml.xstream6.Person>

In fact, every time we call the Add method, there is a persistence process that writes the file to the D:/tmp directory each time.

2, all of our familiar methods of operation

Since Xmlarraylist, XmlMap, and xmlset inherit our familiarity with the various collection interfaces, we can manipulate our data to manipulate lists, maps, and sets, unlike the data in our collection in memory, which is now in our pre-defined persistence strategy.

Write the following procedure:

Java code
  1. Package CN.TJPU.ZHW.XML.XSTREAM6;
  2. Import Java.io.File;
  3. Import Java.util.Iterator;
  4. Import java.util.List;
  5. Import Com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
  6. Import Com.thoughtworks.xstream.persistence.PersistenceStrategy;
  7. Import com.thoughtworks.xstream.persistence.XmlArrayList;
  8. public class Usagetestmain {
  9. The use of xmlarraylist
  10. public static void Main (string[] args) {
  11. Create persistence policies (define storage tools and storage locations)
  12. Note: D:/tmp is an existing directory, otherwise it will error
  13. Persistencestrategy strategy = new Filepersistencestrategy (New File (
  14. "D:/tmp"));
  15. Create an Action tool
  16. List List = new Xmlarraylist (strategy);
  17. System.out.println ("list.size () =" +list.size () when the Xmlarraylist object was created);
  18. System.out.println ();
  19. Get iterators
  20. Iterator iter = List.iterator ();
  21. SYSTEM.OUT.PRINTLN ("****** traversal of each element ******");
  22. Iterate through each of the elements
  23. while (Iter.hasnext ()) {
  24. Person P = (person) iter.next ();
  25. SYSTEM.OUT.PRINTLN ("Current element p=" +p);
  26. }
  27. }
  28. }

Operation Result:

Java code
    1. List.size () =3 when the Xmlarraylist object was first created
    2. Iterate through every element of ******
    3. The name= of the current element P=person object Zhang San
    4. The current element P=person object Name= Fluffy
    5. Current element P=person Object Name= Big Bear

3. Customize your own converter (Local Converter)

Because of the large amount of data stored in memory, we can use file system staging, in memory only the directory where the files are stored, we can define a converter ourselves:

Java code
  1. Package CN.TJPU.ZHW.XML.XSTREAM6;
  2. Import Java.io.File;
  3. Import java.util.ArrayList;
  4. Import java.util.Collection;
  5. Import Com.thoughtworks.xstream.XStream;
  6. Import Com.thoughtworks.xstream.converters.Converter;
  7. Import Com.thoughtworks.xstream.converters.MarshallingContext;
  8. Import Com.thoughtworks.xstream.converters.UnmarshallingContext;
  9. Import Com.thoughtworks.xstream.io.HierarchicalStreamReader;
  10. Import Com.thoughtworks.xstream.io.HierarchicalStreamWriter;
  11. Import Com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
  12. Import com.thoughtworks.xstream.persistence.XmlArrayList;
  13. Define a local converter yourself
  14. Public final class Localarraylistconverter implements Converter {
  15. Private XStream XStream;
  16. Public Localarraylistconverter (XStream XStream) {
  17. This.xstream = XStream;
  18. }
  19. Serializing an collection object to a file
  20. Note: The contents of the collection are not stored in memory while serializing, only the directory in which these files are stored is staged
  21. public void Marshal (Object source, hierarchicalstreamwriter writer,
  22. Marshallingcontext context) {
  23. File dir = new file ("D:/tmp");
  24. Create a persistence tool and load all the files in the directory
  25. Xmlarraylist list = new Xmlarraylist (
  26. New Filepersistencestrategy (Dir,xstream));
  27. Context.convertanother (dir);
  28. Generating files
  29. List.addall ((Collection) source);
  30. }
  31. Read information from a file, reverse-sequence to collection object
  32. Note: All files in the staging directory are deleted when deserializing
  33. Public Object Unmarshal (
  34. Hierarchicalstreamreader Reader,
  35. Unmarshallingcontext context) {
  36. File directory = (file) context.convertanother (null, file.class);
  37. Create a persistence tool and load all the files in the directory
  38. Xmlarraylist persistentlist = new Xmlarraylist (
  39. New Filepersistencestrategy (directory, XStream));
  40. Copy the loaded information to the list
  41. ArrayList list = new ArrayList (persistentlist);
  42. Delete all Files
  43. Persistentlist.clear ();
  44. Returns information that has been loaded
  45. return list;
  46. }
  47. public boolean Canconvert (Class type) {
  48. return type = = Arraylist.class;
  49. }
  50. }

This converter is the conversion of ArrayList objects.

Here are our test procedures:

Java code
  1. Package CN.TJPU.ZHW.XML.XSTREAM6;
  2. Import java.util.ArrayList;
  3. Import java.util.Collection;
  4. Import java.util.List;
  5. Import Com.thoughtworks.xstream.XStream;
  6. public class Localconvertermain {
  7. public static void Main (string[] args) {
  8. XStream XStream = new XStream ();
  9. Xstream.alias ("volume", Volume.class);
  10. Use a custom converter localarraylistconverter to convert the documents field of the volume class
  11. This converter is a limited local converter and can only convert the documents field of the volume class
  12. Xstream.registerlocalconverter (Volume.class, "documents",
  13. New Localarraylistconverter (XStream));
  14. The object to convert
  15. Volume Volume = new Volume ();
  16. Create a Collection
  17. Collection coll = new ArrayList ();
  18. Coll.add (1);
  19. Coll.add (2.123d);
  20. Coll.add (New person ("Zhang San"));
  21. Volume.documents.addAll (coll);
  22. SYSTEM.OUT.PRINTLN ("****** serialization ******");
  23. Convert XML
  24. String XML = xstream.toxml (volume);
  25. Output XML
  26. SYSTEM.OUT.PRINTLN (XML);
  27. SYSTEM.OUT.PRINTLN ("****** deserialization ******");
  28. Volume v2 = (Volume) xstream.fromxml (XML);
  29. for (Object obj:v2.documents) {
  30. System.out.println ("obj=" +obj);
  31. }
  32. }
  33. }
  34. Abstract class Abstractdocument {
  35. String title;
  36. }
  37. Class TextDocument extends Abstractdocument {
  38. List chapters = new ArrayList ();
  39. }
  40. Class Scanneddocument {
  41. List images = new ArrayList ();
  42. }
  43. Class Volume {
  44. List documents = new ArrayList ();
  45. }

Operation Result:

Java code
    1. Serialization of ******
    2. <volume>
    3. <documents>d:\tmp</documents>
    4. </volume>
    5. deserialization ******
    6. Name= Zhang San for Obj=person objects
    7. Obj=person object of Name= Fluffy
    8. Obj=person object of Name= Big Bear
    9. Obj=1
    10. Obj=2.123
    11. Name= Zhang San for Obj=person objects

Using XStream is the implementation of XML and Java Object Conversion (6)--persistence

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.