Java XML JAXB Serialize deserializeFile(String path, Class clazz)

Here you can find the source of deserializeFile(String path, Class clazz)

Description

Reads a file and deserializes it to an object of given class.

License

Apache License

Parameter

Parameter Description
path where the file is located
clazz type of the resulting object

Return

an object of given class

Declaration

public static <T> T deserializeFile(String path, Class<T> clazz) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.FileInputStream;
import java.io.FileNotFoundException;

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

import javax.xml.bind.Unmarshaller;

public class Main {
    /**/*from   w  w  w.j a v a 2  s .  co  m*/
     * Reads a file and deserializes it to an object of given class. 
     * @param path where the file is located
     * @param clazz type of the resulting object
     * @return an object of given class
     */
    public static <T> T deserializeFile(String path, Class<T> clazz) {
        try {

            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller m = context.createUnmarshaller();
            Object o = m.unmarshal(new FileInputStream(path));
            return clazz.cast(o);

        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. deserialize(Element elmnt, Class cls)
  2. deserialize(File fXMLFilePath, Class cls)
  3. deserialize(final Class clazz, final String json)
  4. deserialize(Path input, Class clazz)
  5. deserialize(String data, String className)
  6. deserializeFromXmlFile(T defaultObject, String fileName)
  7. deserializeXmlToJava(String valueType, Serializable value)
  8. save(Class confClass, Object confObj, File xmlFile)
  9. save(File file, T obj, Class... clazz)