Java XML JAXB Serialize saveObject(Path path, T object)

Here you can find the source of saveObject(Path path, T object)

Description

Saves the object to the file.

License

Apache License

Parameter

Parameter Description
T the object type.
path the XML file.
object the object to be saved.

Declaration

public static <T> void saveObject(Path path, T object) 

Method Source Code

//package com.java2s;
/*/* w w w.j a v a2s.  c om*/
 * Copyright 2015 Andrej_Petras.
 *
 * 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.nio.file.Path;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

public class Main {
    /**
     * Saves the object to the file.
     *
     * @param <T> the object type.
     * @param path the XML file.
     * @param object the object to be saved.
     */
    public static <T> void saveObject(Path path, T object) {

        if (path == null || object == null) {
            throw new RuntimeException("The path to file or object is null!");
        }

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            jaxbMarshaller.marshal(object, path.toFile());
        } catch (Exception ex) {
            throw new RuntimeException("Error saving the object to path " + path.toString(), ex);
        }
    }
}

Related

  1. deserializeXmlToJava(String valueType, Serializable value)
  2. save(Class confClass, Object confObj, File xmlFile)
  3. save(File file, T obj, Class... clazz)
  4. saveDataToFile(File file, T data)
  5. saveModel(JAXBElement model, String packageName)
  6. saveObject(T object, Class typeClass, URL path)
  7. saveToFile(String fileName, T obj)
  8. saveXML(Object object, String fileNamePath, Boolean append)
  9. serialiseObject(Object obj, Class objclass)