views:

73

answers:

2

This is code to write hashtable to .txt file !

public static void save(String filename, Map<String, String> hashtable) throws IOException {
    Properties prop = new Properties();
    prop.putAll(hashtable);
    FileOutputStream fos = new FileOutputStream(filename);
    try {
       prop.store(fos, prop);
    } finally {
       fos.close();
    }
}

How we getback the hashtable from that file ? Thanks

+3  A: 

In the very same ugly manner:

@SuppressWarnings("unchecked")
public static Map<String, String> load(String filename) throws IOException {
    Properties prop = new Properties();
    FileInputStream fis = new FileInputStream(filename);
    try {
        prop.load(fis);
    } finally {
        fis.close();
    }
    return (Map) prop;
}
Henning
thanks for your help
tiendv
+1  A: 

Use Properties.load()

code example:

public static Properties load(String filename) {
    FileReader reader = new FileReader(filename);
    Properties props = new Properties();
    try{
        properties.load(reader);
    } finally {
        reader.close();
    }
    return props;
}

Edit:

If you want a map back, use something like this. (The toString is to avoid a cast - you can cast to String if you would prefer)

public static Map<String, String> load(String filename) {
    FileReader reader = new FileReader(filename);
    Properties props = new Properties();
    try {
        properties.load(reader);
    } finally {
        reader.close();
    }
    Map<String, String> myMap = new HashMap<String, String>();
    for (Object key : props.keySet()) {
        myMap.put(key.toString(), props.get(key).toString());
    }
    return myMap;
}
aperkins
thanks for your help
tiendv