【问题标题】:Want to read file in key value form in java想在java中以键值形式读取文件
【发布时间】:2015-02-16 05:27:13
【问题描述】:

我需要在java中读取一个文件,文件格式如下:

type=abc, name=xyz, value=abc123
type=aaa, name=zzz, value=abc456
type=bbb, name=ccc, value=abc001

所以我想将此文件作为键值对读取,那么读取此文件的最佳方式是什么?

请注意,这不是属性文件。

【问题讨论】:

  • 由“,”分割,然后由“=”分割
  • 逐行读取文件并使用正则表达式提取必要的数据。
  • @amuser 以下任何答案是否回答了您的问题?如果是这样,请单击复选框将其标记为正确。如果没有,请告诉我们出了什么问题。

标签: java


【解决方案1】:

逐行读入文件,然后使用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
};

【讨论】:

  • 由于逗号后面有一个空格,可能还需要包含一些trim() 调用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 2012-10-06
  • 1970-01-01
  • 1970-01-01
  • 2012-03-26
  • 2012-04-17
相关资源
最近更新 更多