Reputation: 609
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.
Upvotes: 1
Views: 5343
Reputation: 7018
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());
}
Upvotes: 4