自己写的两个练习

来源:互联网 发布:淘宝运动鞋店铺排行榜 编辑:程序博客网 时间:2024/05/21 11:32

//文件存储ArrayList


public class Data {


    public ArrayList<Message> read() {
        ArrayList<Message> list=new ArrayList<Message>();
        ObjectInputStream ois=null;
        File file =new File("e:"+File.separator+"message.txt");
        if(file.length()!=0){
            try {
                ois=new ObjectInputStream(new FileInputStream(file));
                if(ois!=null){
                    list=(ArrayList<Message>) ois.readObject();
                }
            } catch (IOException | ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return list;

    }
    public void write(ArrayList<Message> list){
        ObjectOutputStream oos=null;
        File file =new File("e:"+File.separator+"message.txt");
        try {
            oos=new ObjectOutputStream(new FileOutputStream(file));
            oos.writeObject(list);
            oos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

xml文件写入
public class ObjectAndXmlHandle {
    public static void ObjectToXml(Object object){
        try {
            JAXBContext context=JAXBContext.newInstance(object.getClass());
            Marshaller marshaller=context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);//是否换行
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);//忽略开头
            marshaller.setProperty(Marshaller.JAXB_ENCODING, "GBK");//解析格式
            OutputStream oStream=new FileOutputStream("e:"+File.separator+"testPerson.xml",true);//输出路径
//            marshaller.marshal(object, oStream);
            marshaller.marshal(object, System.out);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}
0 0
原创粉丝点击