Saves a java object to a xml file. - Android XML

Android examples for XML:JAXB

Description

Saves a java object to a xml file.

Demo Code

/**//from  w ww .jav  a  2  s.  c  o  m
 *  Copyright 2009 Welocalize, Inc. 
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  
 *  You may obtain a copy of the License at 
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  
 */
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.log4j.Logger;

public class Main{
    public static void main(String[] argv) throws Exception{
        Object ob = "java2s.com";
        String filePath = "java2s.com";
        save(ob,filePath);
    }
    private static Logger log = Logger.getLogger(XmlUtil.class);
    /**
     * Saves a java object to a xml file. If the file has been exist, it will be
     * covered.
     * 
     * @param ob
     *            The java object to save. Can't be null.
     * @param filePath
     *            The path of xml file.
     */
    public static void save(Object ob, String filePath) {
        log.debug("Saving to " + filePath);

        Assert.assertNotNull(ob, "Object to save");
        Assert.assertNotNull(filePath, "File path");

        FileWriter fw = null;
        try {
            JAXBContext context = JAXBContext.newInstance(ob.getClass());
            Marshaller m = context.createMarshaller();
            m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            fw = new FileWriter(filePath);
            m.marshal(ob, fw);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }

        log.debug("Saving finished");
    }
}

Related Tutorials