www.pudn.com > GMapViewer-src.zip > Properties.java



package org.sreid.j2me.util;

import java.util.*;
import java.io.*;

/**
 * Subclass of Hashtable that supports only Strings,
 * and can be serialized to and from a byte array.
 */
public class Properties extends Hashtable {

	public Object put(Object key, Object value) {
		// Prevent non-Strings from being inserted
		return super.put((String)key, (String)value);
	}

	/** Returns the value for the specified key. */
	public String getString(String key) {
		return (String)get(key);
	}

	/** Returns the value of the specified key, or defaultValue if null. */
	public String getString(String key, String defaultValue) {
		String s = (String)get(key);
		return (s != null ? s : defaultValue);
	}

	/** Returns the value of the specified key as an int, or 0 if not a valid int. */
	public int getInt(String key) {
		return getInt(key, 0);
	}

	/** Returns the value of the specified key as an int, or defaultValue if not a valid int. */
	public int getInt(String key, int defaultValue) {
		try {
			return Integer.parseInt(getString(key));
		}
		catch (Exception e) {
			return defaultValue;
		}
	}

	/** Saves all key/value pairs to a byte array. */
	public synchronized byte[] save() {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		try {
			save(dos);
		}
		catch (IOException e) {
			throw new Error("Somehow got an IOException writing to a ByteArrayOutputStream: " + e);
		}
		finally {
			try { dos.close(); } catch (Exception e) { }
			try { baos.close(); } catch (Exception e) { }
		}
		return baos.toByteArray();
	}

	/** Saves all key/value pairs to the specified DataOutput. */
	public synchronized void save(DataOutput out) throws IOException {
		out.writeInt(size());
		for (Enumeration e = keys() ; e.hasMoreElements() ; ) {
			String key = (String)e.nextElement();
			String val = getString(key);
			out.writeUTF(key);
			out.writeUTF(val);
		}
	}

	/** Adds the key/value pairs from previously saved data. */
	public synchronized void load(byte[] data) {
		ByteArrayInputStream bais = new ByteArrayInputStream(data);
		DataInputStream dis = new DataInputStream(bais);
		try {
			load(dis);
		}
		catch (IOException e) {
			throw new IllegalArgumentException("Exception reading data: " + e);
		}
		finally {
			try { dis.close(); } catch (Exception e) { }
			try { bais.close(); } catch (Exception e) { }
		}
	}

	/** Adds the key/value pairs from previously saved data. */
	public synchronized void load(DataInput in) throws IOException {
		int size = in.readInt();
		for (int i = 0; i < size; i++) {
			String key = in.readUTF();
			String val = in.readUTF();
			put(key, val);
		}
	}
}