如何将 XMLEncoder 和 XMLDecoder 与 String 一起使用?
How to use XMLEncoder and XMLDecoder with String?
抱歉,这是 Java 的新问题!
如何将一个字符串输入到 XMLEncoder 并从 XMLDecoder 输出一个字符串?
字符串包含有关 JavaBeans 对象的信息。
这是一个使用 ByteArrayInput/OutputStream 比另一个问题更直接的例子:
对于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;
}
}
读取或写入:
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());
}
抱歉,这是 Java 的新问题!
如何将一个字符串输入到 XMLEncoder 并从 XMLDecoder 输出一个字符串?
字符串包含有关 JavaBeans 对象的信息。
这是一个使用 ByteArrayInput/OutputStream 比另一个问题更直接的例子:
对于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;
}
}
读取或写入:
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());
}