首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在字符串中使用XMLEncoder和XMLDecoder?

如何在字符串中使用XMLEncoder和XMLDecoder?
EN

Stack Overflow用户
提问于 2015-11-28 11:40:18
回答 1查看 4.3K关注 0票数 1

对不起,这是Java的一个非常新的问题!

如何将字符串输入到XMLEncoder,如何从XMLDecoder输出字符串?

该字符串包含有关JavaBeans对象的信息。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-28 12:05:00

下面是一个比其他问题更直接地使用ByteArrayInput/OutputStream的示例:

上课用

代码语言:javascript
复制
static public class MyClass implements Serializable {

    private String prop;

    /**
     * Get the value of prop
     *
     * @return the value of prop
     */
    public String getProp() {
        return prop;
    }

    /**
     * Set the value of prop
     *
     * @param prop new value of prop
     */
    public void setProp(String prop) {
        this.prop = prop;
    }

}

读或写:

代码语言:javascript
复制
static String toString(MyClass obj) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder e = new XMLEncoder(baos);
    e.writeObject(obj);
    e.close();
    return new String(baos.toByteArray());
}

static MyClass fromString(String str) {
    XMLDecoder d = new XMLDecoder(new ByteArrayInputStream(str.getBytes()));
    MyClass obj = (MyClass) d.readObject();
    d.close();
    return obj;
}
public static void main(String[] args) {

    MyClass obj = new MyClass();
    obj.setProp("propval");
    String s = toString(obj);
    System.out.println("s = " + s);
    MyClass obj2 = fromString(s);
    System.out.println("obj2.getProp() = " + obj2.getProp());
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33970909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档