How do I return a map from a .txt file to use properties?

This is the code to write a hash table to a .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 do we get the hash table from this file? Thanks to

+2


a source to share


2 answers


Use Properties.load()

Sample code

:

public static Properties load(String filename) {
    FileReader reader = new FileReader(filename);
    Properties props = new Properties(); // The variable name must be used as props all along or must be properties
    try{
        props.load(reader);
    } finally {
        reader.close();
    }
    return props;
}

      




Edit:

If you want to return the card, use something like this. (ToString should avoid casting - you can use String if you like)

public static Map<String, String> load(String filename) {
    FileReader reader = new FileReader(filename);
    Properties props = new Properties();
    try {
        props.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;
}

      

+2


a source


In the same ugly way:



@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;
}

      

+4


a source







All Articles