[英]How to get back Map from .txt file use Properties?
This is code to write hashtable to .txt file ! 这是将哈希表写入.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();
}
}
How we getback the hashtable from that file ? 我们如何从该文件取回哈希表? Thanks
谢谢
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;
}
Use Properties.load()
使用
Properties.load()
code example: 代码示例:
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 a map back, use something like this. 如果您想返回地图,请使用类似的内容。 (The toString is to avoid a cast - you can cast to String if you would prefer)
(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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.