com.github.lespaul361.commons.commonroutines.utilities.SerializationUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of Commons-CommonRoutines Show documentation
Show all versions of Commons-CommonRoutines Show documentation
common routines I use in my projects
/*
* Copyright (C) 2019 Charles Hamilton
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
package com.github.lespaul361.commons.commonroutines.utilities;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* A simple class with generic serialize and deserialize method implementations
*
* @author pankaj
*
*/
public class SerializationUtil {
// deserialize to Object from given file
/**
* Opens a serialized object
*
* @param fileName
* the full path to the serialized object
* @return Object
that is the serialized object
* @throws IOException
* an error reading the file
* @throws ClassNotFoundException
* class reading error
*/
public static Object deserialize(String fileName) throws IOException, ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
ois.close();
return obj;
}
// serialize the given object and save it to file
/**
* Saves an object to a file
*
* @param obj
* the object to be saved
* @param fileName
* the full path of the file to save the information in
* @throws IOException
* an error writing the file
*/
public static void serialize(Object obj, String fileName) throws IOException {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);
fos.close();
}
}