通過XMLEncoder生成XML檔案
阿新 • • 發佈:2019-01-26
先定義一需要建立的XMl的類,裡面放需要的屬性
public class Person {
String person;
String name;
int age;
String sex;
int tel;
public String getPerson() {
return person;
}
public void setPerson(String person) {
this.person = person;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this .sex = sex;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
public Person() {
super();
}
protected Person(String person, String name, int age, String sex, int tel) {
super();
this.person = person;
this .name = name;
this.age = age;
this.sex = sex;
this.tel = tel;
}
@Override
public String toString() {
return "Person [person=" + person + ", name=" + name + ", age=" + age
+ ", sex=" + sex + ", tel=" + tel + "]";
}
}
public class XmlEncodeDemo {
public static void main(String[] args) {
//注意Person裡面的屬性定義都是public
Person p=new Person("1","小王",18,"nv",134);
Person p2=new Person("2","小王",18,"nv",134);
BufferedOutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream("D:\\person.xml"));
XMLEncoder encode=new XMLEncoder(out);
encode.writeObject(p);
encode.writeObject(p2);
encode.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}