⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 propertiesconverter.java

📁 xstream是一个把java object序列化成xml文件的开源库,轻便好用
💻 JAVA
字号:
package com.thoughtworks.xstream.converters.collections;import com.thoughtworks.xstream.converters.Converter;import com.thoughtworks.xstream.converters.MarshallingContext;import com.thoughtworks.xstream.converters.UnmarshallingContext;import com.thoughtworks.xstream.converters.ConversionException;import com.thoughtworks.xstream.io.HierarchicalStreamReader;import com.thoughtworks.xstream.io.HierarchicalStreamWriter;import com.thoughtworks.xstream.core.util.Fields;import java.util.Iterator;import java.util.Map;import java.util.Properties;import java.lang.reflect.Field;/** * Special converter for java.util.Properties that stores * properties in a more compact form than java.util.Map. * <p/> * <p>Because all entries of a Properties instance * are Strings, a single element is used for each property * with two attributes; one for key and one for value.</p> * <p>Additionally, default properties are also serialized, if they are present.</p> * * @author Joe Walnes * @author Kevin Ring */public class PropertiesConverter implements Converter {    private final Field defaultsField = Fields.find(Properties.class, "defaults");    public boolean canConvert(Class type) {        return Properties.class == type;    }    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {        Properties properties = (Properties) source;        for (Iterator iterator = properties.entrySet().iterator(); iterator.hasNext();) {            Map.Entry entry = (Map.Entry) iterator.next();            writer.startNode("property");            writer.addAttribute("name", entry.getKey().toString());            writer.addAttribute("value", entry.getValue().toString());            writer.endNode();        }        Properties defaults = (Properties) Fields.read(defaultsField, properties);        if (defaults != null) {            writer.startNode("defaults");            marshal(defaults, writer, context);            writer.endNode();        }    }    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {        Properties properties = new Properties();        while (reader.hasMoreChildren()) {            reader.moveDown();            if (reader.getNodeName().equals("defaults")) {                Properties defaults = (Properties) unmarshal(reader, context);                Fields.write(defaultsField, properties, defaults);            } else {                String name = reader.getAttribute("name");                String value = reader.getAttribute("value");                properties.setProperty(name, value);            }            reader.moveUp();        }        return properties;    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -