2010-05-11 20 views
10

Tengo un Hashtable<string,string>, en mi programa quiero registrar los valores de la Hashtable para procesarlos más tarde.¿Podemos escribir una Hashtable en un archivo?

Mi pregunta es: ¿podemos escribir el objeto Hastable en un archivo? Si es así, ¿cómo podemos cargar ese archivo más tarde?

Respuesta

9

Sí, utilizando la serialización binaria (ObjectOutputStream):

FileOutputStream fos = new FileOutputStream("t.tmp"); 
ObjectOutputStream oos = new ObjectOutputStream(fos); 

oos.writeObject(yourHashTable); 
oos.close(); 

continuación, puede leer usando ObjectInputStream

Los objetos que se colocan en el interior del Hashtable (o mejor - HashMap) tienen que implementar Serializable


Si desea almacenar el Hashtable en un formato legible por humanos, puede utilizar java.beans.XMLEncoder:

FileOutputStream fos = new FileOutputStream("tmp.xml"); 
XMLEncoder e = new XMLEncoder(fos); 
e.writeObject(yourHashTable); 
e.close(); 
+0

Gracias por su respuesta! Tengo pregunta mi hastable ¿Cómo puedo escribir en el archivo XML como //// //// tiendv

+0

Puede usar algo como XStream o JAXB para personalizar el xml, pero es demasiado dolor de cabeza. Me quedaría con XMLEncoder, o con la solución 'Propiedades' propuesta. – Bozho

5

No sé acerca de su aplicación específica, pero puede que desee echar un vistazo a la Properties class. (Se extiende HashMap.)

Esta categoría cuenta con unas

void load(InputStream inStream) 
    Reads a property list (key and element pairs) from the input byte stream. 
void load(Reader reader) 
    Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format. 
void loadFromXML(InputStream in) 
    Loads all of the properties represented by the XML document on the specified input stream into this properties table. 
void store(Writer writer, String comments) 
     Writes this property list (key and element pairs) in this Properties table to the output character stream in a format suitable for using the load(Reader) method. 
void storeToXML(OutputStream os, String comment) 
     Emits an XML document representing all of the properties contained in this table. 

The tutorial es bastante educativo también.

1

Si desea poder editar fácilmente el mapa una vez que está escrito, es posible que desee echar un vistazo a jYaml. Le permite escribir fácilmente el mapa en un archivo con formato Yaml, lo que significa que es fácil de leer y editar.

0

También es posible usar MapDB y se ahorrará el HashMap para usted después de hacer un put y una commit. De esta forma, si el programa falla, los valores seguirán vigentes.

Cuestiones relacionadas