Bean与XML相互转化
实现Java对象与XML之间相互转化:
?
User类:
public class User {private Long id;private String name;private String password;//getter...setterpublic Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString(){System.out.println(new StringBuffer().append("id:").append(this.getId()).append(";name:").append(this.getName()).append(";password:").append(this.getPassword()));return "" ;}}
?
?
?
实现相互转化的类:
import java.beans.XMLDecoder;import java.beans.XMLEncoder;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;public class BeanToXML {public static void main(String[] args) {User user = new User();user.setId(new Long(1)) ;user.setName("JLee 哈哈") ;user.setPassword("111") ;try {XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("User.xml")));// 使用writeObject方法把Bean输出为XML文件encoder.writeObject(user);encoder.close();} catch (FileNotFoundException e) {e.printStackTrace();}try {XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream("User.xml"))) ;// 使用readObject方法把Bean从XML文件中读取出来User jlee = (User)decoder.readObject() ;System.out.println(jlee);decoder.close() ;} catch (FileNotFoundException e) {e.printStackTrace();}}}
?
?
简单明了,希望对大家有帮助!