Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用带字符串的XMLEncoder和XMLDecoder?_Java_Javabeans - Fatal编程技术网

Java 如何使用带字符串的XMLEncoder和XMLDecoder?

Java 如何使用带字符串的XMLEncoder和XMLDecoder?,java,javabeans,Java,Javabeans,抱歉,这是一个非常新的Java问题 如何将字符串输入到XMLEncoder,如何从XMLDecoder输出字符串 该字符串包含有关JavaBeans对象的信息。这里有一个使用ByteArrayInput/OutputStream比其他问题更直接的示例: 上课 static public class MyClass implements Serializable { private String prop; /** * Get the value of prop

抱歉,这是一个非常新的Java问题

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


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

这里有一个使用ByteArrayInput/OutputStream比其他问题更直接的示例:

上课

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;
    }

}
读或写:

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());
}
试试这个: