2010-05-11 20 views
10

Ho un Hashtable<string,string>, nel mio programma voglio registrare i valori di Hashtable da elaborare in seguito.Possiamo scrivere un Hashtable su un file?

La mia domanda è: possiamo scrivere l'oggetto Hastable in un file? Se è così, come possiamo caricare in seguito quel file?

risposta

9

Sì, utilizzando la serializzazione binaria (ObjectOutputStream):

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

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

Quindi è possibile leggerlo con ObjectInputStream

Gli oggetti che si inserisce all'interno del Hashtable (o meglio - HashMap) devono implementare Serializable


Se si desidera memorizzare Hashtable in un formato leggibile, è possibile utilizzare java.beans.XMLEncoder:

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

Grazie della risposta! Ho domanda mia hastable Come posso scrivere nel file XML come //// //// tiendv

+0

È possibile utilizzare qualcosa come XStream o JAXB per personalizzare l'xml, ma è troppo mal di testa. Rimanerei con XMLEncoder, o con la proposta soluzione 'Properties'. – Bozho

5

Non so la vostra applicazione specifica, ma si potrebbe desiderare di avere uno sguardo alla Properties class. (Si estende hashmap.)

Questa classe fornisce

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 è molto educativo anche.

1

Se si desidera poter modificare facilmente la mappa una volta scritta, è possibile dare un'occhiata a jYaml. Ti permette di scrivere facilmente la mappa su un file in formato Yaml, il che significa che è facile da leggere e modificare.

0

Si potrebbe anche usare MapDB e sarà salvare il HashMap per voi dopo aver fatto un put e commit. In questo modo, se il programma si arresta in modo anomalo, i valori continueranno a essere persistenti.

Problemi correlati