2010-05-12 22 views
2

這是將hashtable寫入.txt文件的代碼!如何從.txt文件中取回地圖使用屬性?

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(); 
    } 
} 

我們如何從該文件中取回散列表? 由於

+2

請記住接受(最好)幫助您解決問題的答案。使用答案左側的綠色複選標記。 – Jonik 2010-05-12 20:33:23

回答

2

使用Properties.load()

代碼例如:

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

編輯:

如果你想返回地圖,請使用類似這樣的東西。 (toString是爲了避免演員陣容 - 如果您願意,可以投射到String)

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; 
} 
+0

感謝您的幫助 – tiendv 2010-05-12 20:08:54

4

以非常相似的方式難看:

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

感謝您的幫助 – tiendv 2010-05-12 20:09:25

相關問題