如何将XMLEncoder和XMLDecoder与String一起使用? [英] How to use XMLEncoder and XMLDecoder with String?
本文介绍了如何将XMLEncoder和XMLDecoder与String一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
抱歉,这是Java的一个非常新的问题!
Sorry this is a very new to Java question!
如何将一个字符串输入XMLEncoder并从XMLDecoder输出一个字符串?
How does one input a String to XMLEncoder and one output a String from XMLDecoder?
该字符串包含有关JavaBeans对象的信息.
The String contains information about a JavaBeans object.
推荐答案
与其他问题相比,这里是使用ByteArrayInput/OutputStream的更直接的示例:
Here is a more direct example using ByteArrayInput/OutputStream than the other question:
上课
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());
}
这篇关于如何将XMLEncoder和XMLDecoder与String一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文