javaBean转换为xml文件,将xml转换成javaBean,可以用jox,虽然jox有点缺点,但是确实是很方便,我今天写了一个java项目,使用了jox,共有三个文件
1.首先见一个User.java文件,这是个javaBean
package com.jox;
public class User {
private int id;
private String username;
private String password;
public User(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", password=" + password + ", username="
+ username + "]";
}
}
package com.jox;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import com.wutka.jox.JOXBeanInputStream;
import com.wutka.jox.JOXBeanOutputStream;
import com.wutka.jox.JOXBeanReader;
import com.wutka.jox.JOXBeanWriter;
public class Tools {
public static void fileWriter(User user, String path) throws Exception{
Writer writer = new FileWriter(path);
JOXBeanWriter joxBeanWriter = new JOXBeanWriter(writer);
joxBeanWriter.writeObject(user.getClass().getSimpleName(), user);
joxBeanWriter.close();
writer.close();
}
public static User fileReader(String path) throws Exception{
Reader reader = new FileReader(path);
JOXBeanReader joxBeanReader = new JOXBeanReader(reader);
User user = (User) joxBeanReader.readObject();
joxBeanReader.close();
reader.close();
return user;
}
public static User fileInput(String path) throws Exception{
InputStream inputStream = new FileInputStream(path);
JOXBeanInputStream joxBeanInputStream = new JOXBeanInputStream(inputStream);
User user = (User)joxBeanInputStream.readObject();
joxBeanInputStream.close();
inputStream.close();
return user;
}
public static void fileOutput(User user, String path) throws Exception{
OutputStream outputStream = new FileOutputStream(path);
JOXBeanOutputStream joxBeanOutputStream = new JOXBeanOutputStream(outputStream);
joxBeanOutputStream.writeObject(user.getClass().getSimpleName(), user);
joxBeanOutputStream.close();
outputStream.close();
}
}
package com.jox;
public class Client {
public static void main(String[] args) throws Exception {
User user1 = new User();
user1.setId(1);
user1.setPassword("111");
user1.setUsername("张三");
User user2 = new User();
user2.setId(2);
user2.setPassword("222");
user2.setUsername("李四");
//Tools.fileOutput(user1, "D:\\user.xml");
//Tools.fileWriter(user2, "D:\\user2.xml");
User user3 = Tools.fileInput("D:\\user.xml");
User user4 = Tools.fileReader("D:\\user2.xml");
System.out.println(user3.toString());
System.out.println(user4.toString());
}
}