All Downloads are FREE. Search and download functionalities are using the official Maven repository.

info.hargrave.configuration.medium.SerializedConfigurationFile Maven / Gradle / Ivy

The newest version!
package info.hargrave.configuration.medium;

import info.hargrave.configuration.ConfigurationMedium;
import info.hargrave.configuration.Serializer;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * ConfigurationMedium that stores the configuration on the disk simply be serializing the configuration map
 */
public final class SerializedConfigurationFile implements ConfigurationMedium {

    private final File configurationStore;
    private final Serializer serializerImplementation;

    public SerializedConfigurationFile(File configurationFile, Serializer serializer){
        configurationStore = configurationFile;
        serializerImplementation = serializer;
    }

    @Override
    public void commitConfiguration(HashMap configuration) throws IOException {

        byte[] serialFileData = serializerImplementation.serialize(configuration);

        FileOutputStream _fos = new FileOutputStream(configurationStore);
        _fos.write(serialFileData);
        _fos.flush();
        _fos.close();

    }

    @Override
    @SuppressWarnings("unchecked") // Should except if incorrect
    public HashMap readConfiguration() throws IOException {

        FileInputStream _fis = new FileInputStream(configurationStore);
        byte[] serialFileData = IOUtils.toByteArray(_fis);


        try {
            return (HashMap) serializerImplementation.deSerialize(serialFileData, HashMap.class);
        } catch (ClassNotFoundException e) {
            throw new IOException("Could not read file data");
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy