Java tutorial
package com.codercowboy.photo.organizer.service; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; import com.codercowboy.photo.organizer.service.v1.Library; /* * Copyright 2015 Jason Baker * 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. */ public class LibraryMarshaller { transient private JAXBContext ctx = null; private JAXBContext createContext() throws JAXBException { if (ctx == null) { ctx = JAXBContext.newInstance(Library.class.getPackage().getName()); } return ctx; } public void saveLibrary(Library library, String fileName) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try { Marshaller marshaller = this.createContext().createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.marshal(library, outputStream); FileUtils.writeByteArrayToFile(new File(fileName), outputStream.toByteArray()); } finally { outputStream.close(); } } public Library loadLibrary(String fileName) throws Exception { byte[] fileData = FileUtils.readFileToByteArray(new File(fileName)); ByteArrayInputStream bais = new ByteArrayInputStream(fileData); try { Unmarshaller unmarshaller = this.createContext().createUnmarshaller(); @SuppressWarnings("unchecked") JAXBElement<Library> jaxbElement = (JAXBElement<Library>) unmarshaller.unmarshal(bais); return jaxbElement.getValue(); } finally { bais.close(); } } }