我需要在java中读取文件,文件格式如下:
type=abc, name=xyz, value=abc123
type=aaa, name=zzz, value=abc456
type=bbb, name=ccc, value=abc001
所以我希望将此文件作为键值对读取,那么读取此文件的最佳方法是什么?
请注意,这不是属性文件。
答案 0 :(得分:2)
逐行读入文件,然后使用string.split(“separator”)将字符串拆分为每个部分。
算法的布局如下:
代码示例
String s = "... content read in from file ..."
String[] pairs = s.split(","); // This would split it into sections divided by the comma, resulting in an array of Strings with elements such as "type=abc"
HashMap<String, String> map = new HashMap<String, String>();
for (String string : pairs) {
String[] keyValue = string.split("="); // Split on the "=" of an element such as "type=abc", resulting in a String array of two elements, "type" and "abc"
map.put(keyValue[0], keyValue[1]); // Store those values however you'd like
};