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
- Package CN.TJPU.ZHW.XML.XSTREAM6;
- Import Java.io.File;
- Import java.util.List;
- Import Com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
- Import Com.thoughtworks.xstream.persistence.PersistenceStrategy;
- Import com.thoughtworks.xstream.persistence.XmlArrayList;
- public class Persistencemain {
- public static void Main (string[] args) {
- Create persistence policies (define storage tools and storage locations)
- Note: D:/tmp is an existing directory, otherwise it will error
- Persistencestrategy strategy = new Filepersistencestrategy (
- New File ("d:/tmp"));
- Create an Action tool
- List List = new Xmlarraylist (strategy);
- System.out.println ("list.size () =" +list.size () when the Xmlarraylist object was created);
- Add data
- List.add (New person ("Zhang San"));
- List.add (New person ("John Doe"));
- List.add (New person ("fluffy"));
- List.add (New person ("Big Bear"));
- System.out.println ("After adding 4 elements list.size () =" +list.size ());
- Delete "John Doe"
- List.remove (1);
- System.out.println ("Removed 1 elements after list.size () =" +list.size ());
- }
- }
- Class Person {
- Public person (String name) {
- THIS.name = name;
- }
- private String name;
- Public String GetName () {
- return name;
- }
- public void SetName (String name) {
- THIS.name = name;
- }
- Public String toString () {
- Return "name= of the Person object" + getName ();
- }
- }
Operation Result:
Java code
- List.size () =0 when the Xmlarraylist object was first created
- After adding 4 elements list.size () =4
- 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
- <cn.tjpu.zhw.xml.xstream6.Person>
- <name> Zhang San </name>
- </cn.tjpu.zhw.xml.xstream6.Person>
[Email protected] File
XML code
- <cn.tjpu.zhw.xml.xstream6.Person>
- <name> Fluffy </name>
- </cn.tjpu.zhw.xml.xstream6.Person>
[Email protected] File:
XML code
- <cn.tjpu.zhw.xml.xstream6.Person>
- <name> Big Bear </name>
- </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
- Package CN.TJPU.ZHW.XML.XSTREAM6;
- Import Java.io.File;
- Import Java.util.Iterator;
- Import java.util.List;
- Import Com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
- Import Com.thoughtworks.xstream.persistence.PersistenceStrategy;
- Import com.thoughtworks.xstream.persistence.XmlArrayList;
- public class Usagetestmain {
- The use of xmlarraylist
- public static void Main (string[] args) {
- Create persistence policies (define storage tools and storage locations)
- Note: D:/tmp is an existing directory, otherwise it will error
- Persistencestrategy strategy = new Filepersistencestrategy (New File (
- "D:/tmp"));
- Create an Action tool
- List List = new Xmlarraylist (strategy);
- System.out.println ("list.size () =" +list.size () when the Xmlarraylist object was created);
- System.out.println ();
- Get iterators
- Iterator iter = List.iterator ();
- SYSTEM.OUT.PRINTLN ("****** traversal of each element ******");
- Iterate through each of the elements
- while (Iter.hasnext ()) {
- Person P = (person) iter.next ();
- SYSTEM.OUT.PRINTLN ("Current element p=" +p);
- }
- }
- }
Operation Result:
Java code
- List.size () =3 when the Xmlarraylist object was first created
- Iterate through every element of ******
- The name= of the current element P=person object Zhang San
- The current element P=person object Name= Fluffy
- 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
- Package CN.TJPU.ZHW.XML.XSTREAM6;
- Import Java.io.File;
- Import java.util.ArrayList;
- Import java.util.Collection;
- Import Com.thoughtworks.xstream.XStream;
- Import Com.thoughtworks.xstream.converters.Converter;
- Import Com.thoughtworks.xstream.converters.MarshallingContext;
- Import Com.thoughtworks.xstream.converters.UnmarshallingContext;
- Import Com.thoughtworks.xstream.io.HierarchicalStreamReader;
- Import Com.thoughtworks.xstream.io.HierarchicalStreamWriter;
- Import Com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
- Import com.thoughtworks.xstream.persistence.XmlArrayList;
- Define a local converter yourself
- Public final class Localarraylistconverter implements Converter {
- Private XStream XStream;
- Public Localarraylistconverter (XStream XStream) {
- This.xstream = XStream;
- }
- Serializing an collection object to a file
- Note: The contents of the collection are not stored in memory while serializing, only the directory in which these files are stored is staged
- public void Marshal (Object source, hierarchicalstreamwriter writer,
- Marshallingcontext context) {
- File dir = new file ("D:/tmp");
- Create a persistence tool and load all the files in the directory
- Xmlarraylist list = new Xmlarraylist (
- New Filepersistencestrategy (Dir,xstream));
- Context.convertanother (dir);
- Generating files
- List.addall ((Collection) source);
- }
- Read information from a file, reverse-sequence to collection object
- Note: All files in the staging directory are deleted when deserializing
- Public Object Unmarshal (
- Hierarchicalstreamreader Reader,
- Unmarshallingcontext context) {
- File directory = (file) context.convertanother (null, file.class);
- Create a persistence tool and load all the files in the directory
- Xmlarraylist persistentlist = new Xmlarraylist (
- New Filepersistencestrategy (directory, XStream));
- Copy the loaded information to the list
- ArrayList list = new ArrayList (persistentlist);
- Delete all Files
- Persistentlist.clear ();
- Returns information that has been loaded
- return list;
- }
- public boolean Canconvert (Class type) {
- return type = = Arraylist.class;
- }
- }
This converter is the conversion of ArrayList objects.
Here are our test procedures:
Java code
- Package CN.TJPU.ZHW.XML.XSTREAM6;
- Import java.util.ArrayList;
- Import java.util.Collection;
- Import java.util.List;
- Import Com.thoughtworks.xstream.XStream;
- public class Localconvertermain {
- public static void Main (string[] args) {
- XStream XStream = new XStream ();
- Xstream.alias ("volume", Volume.class);
- Use a custom converter localarraylistconverter to convert the documents field of the volume class
- This converter is a limited local converter and can only convert the documents field of the volume class
- Xstream.registerlocalconverter (Volume.class, "documents",
- New Localarraylistconverter (XStream));
- The object to convert
- Volume Volume = new Volume ();
- Create a Collection
- Collection coll = new ArrayList ();
- Coll.add (1);
- Coll.add (2.123d);
- Coll.add (New person ("Zhang San"));
- Volume.documents.addAll (coll);
- SYSTEM.OUT.PRINTLN ("****** serialization ******");
- Convert XML
- String XML = xstream.toxml (volume);
- Output XML
- SYSTEM.OUT.PRINTLN (XML);
- SYSTEM.OUT.PRINTLN ("****** deserialization ******");
- Volume v2 = (Volume) xstream.fromxml (XML);
- for (Object obj:v2.documents) {
- System.out.println ("obj=" +obj);
- }
- }
- }
- Abstract class Abstractdocument {
- String title;
- }
- Class TextDocument extends Abstractdocument {
- List chapters = new ArrayList ();
- }
- Class Scanneddocument {
- List images = new ArrayList ();
- }
- Class Volume {
- List documents = new ArrayList ();
- }
Operation Result:
Java code
- Serialization of ******
- <volume>
- <documents>d:\tmp</documents>
- </volume>
- deserialization ******
- Name= Zhang San for Obj=person objects
- Obj=person object of Name= Fluffy
- Obj=person object of Name= Big Bear
- Obj=1
- Obj=2.123
- Name= Zhang San for Obj=person objects
Using XStream is the implementation of XML and Java Object Conversion (6)--persistence