Java XML JAXB Serialize saveToFile(String fileName, T obj)

Here you can find the source of saveToFile(String fileName, T obj)

Description

save object to xml file using outputStream, JAXNContext and marshaller

License

Open Source License

Parameter

Parameter Description
fileName a parameter
obj object

Declaration

public static <T> void saveToFile(String fileName, T obj) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
    /**//from   www. ja va  2s  .c  o  m
     * save object to xml file using outputStream, JAXNContext and marshaller
     * @param fileName
     * @param obj object
     */
    public static <T> void saveToFile(String fileName, T obj) {
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(fileName);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            // JaxbList<T> jaxbList = new JaxbList<>(list);
            //File file = openFile(fileName);

            //String xsdFilename = fileName + ".xsd";
            JAXBContext jaxbContext = JAXBContext.newInstance(obj.getClass());
            // jaxbContext.generateSchema(new XSDSchemaGenerator(xsdFilename));
            Marshaller marshaller = jaxbContext.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, fileName);
            marshaller.marshal(obj, outputStream);
        } catch (JAXBException e) {
            System.out.println("Error saving file " + e.toString());
        }
    }
}

Related

  1. save(File file, T obj, Class... clazz)
  2. saveDataToFile(File file, T data)
  3. saveModel(JAXBElement model, String packageName)
  4. saveObject(Path path, T object)
  5. saveObject(T object, Class typeClass, URL path)
  6. saveXML(Object object, String fileNamePath, Boolean append)
  7. serialiseObject(Object obj, Class objclass)
  8. serialize(final Object object)
  9. serialize(JAXBElement emp, Class clazz, OutputStream out)