1

Sorry this is a very new to Java question!

How does one input a String to XMLEncoder and one output a String from XMLDecoder?

The String contains information about a JavaBeans object.

1

1 Answer 1

4

Here is a more direct example using ByteArrayInput/OutputStream than the other question:

for class

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

}

read or write with:

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());
}
Sign up to request clarification or add additional context in comments.

1 Comment

You could call baos.toString(StandardCharsets.UTF_8) instead of new String(baos.toByteArray()) (it requires at least Java 10).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.