/* * Copyright (c) 2001 Matthew Feldt. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided the copyright notice above is * retained. * * THIS SOFTWARE IS PROVIDED ''AS IS'' AND WITHOUT ANY EXPRESSED OR * IMPLIED WARRANTIES. */ /** * BinaryProperties.java * * Java Examples In A Nutshell Copyright (c) 2000 David Flanagan * Exercise 9-1: * The java.util.Properties class is essentially a hashtable that maps string * keys to string values. It defines store() and load() methods that save and * load its contents to and from a byte stream. These methods save the Properties * object in a human-readable text format despite the fact that they use * byte streams. Properties inherits the Serializable interface from its super- * class, java.util.Hashtable. Define a subclass of Properties that implements * storeBinary() and loadBinary() methods that use object serialization to * save and load the contents of the Properties object in binary form. You * may also want to use java.util.zip.GZIPOutputStream and java.util.zip.GZIP- * InputStream in your methods to make the binary format particularly compact. * Use the serialver program to obtain a serialVersionUID value for your class. * * @author Matthew Feldt * @version 1.0, 05/27/2001 10:05 */ package com.feldt.examples.serialization; import java.io.*; import java.util.*; import java.util.zip.*; /** * An extension of the java class Properties that implements compressed * binary serialization. */ class BinaryProperties extends Properties { /** serialVersionUID from $JAVA_HOME/bin/serialver. */ static final long serialVersionUID = -626753475793321398L; /** Serialize Property object to File f. */ public static void storeBinary(Properties p, File f) throws IOException { ObjectOutputStream out = new ObjectOutputStream( new GZIPOutputStream(new FileOutputStream(f))); out.writeObject(p); out.close(); } /** Read Property object from serialization data in File f. */ public static Properties loadBinary(File f) throws IOException, ClassNotFoundException { ObjectInputStream in = new ObjectInputStream( new GZIPInputStream(new FileInputStream(f))); return (Properties)in.readObject(); } /** test class */ static class Test { public static void main(String[] args) { final String FILE_NAME = "bp.out"; BinaryProperties bp = new BinaryProperties(); bp.setProperty("one", "first"); bp.setProperty("two", "second"); bp.setProperty("three", "third"); try { bp.storeBinary(bp, new File(FILE_NAME)); // serialize Properties // read the serialized data in to a new object Properties copy = new BinaryProperties().loadBinary(new File(FILE_NAME)); System.out.println(copy); if (copy.equals(bp)) System.out.println("Copies equal."); } catch(IOException e) { System.err.println(e.getMessage()); } catch(ClassNotFoundException e) { System.err.println(e.getMessage()); } } } }