首页 > 解决方案 > Java 配置文件多维数组

问题描述

我有个问题。对于我的代码,我有一个包含以下内容的配置文件:

updateOnInsert=true
removeLast=false

names=Joey Greek, Lisa Blessing, Arnold Verdict

要阅读此配置文件,我有以下代码:

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("configs/main.config");
                
// Read all properties from agent strategy file
Properties properties = new Properties();
properties.load(is);

// Assign all properties to variables
boolean updateOnInsert = Boolean.parseBoolean(properties.getProperty("updateOnInsert"));
boolean removeLast = Boolean.parseBoolean(properties.getProperty("removeLast"));

List<String> names = Arrays.asList(properties.getProperty("names").split(", ", -1));

但现在我需要将名称的格式更改为:

names=[[Joey, Greek], [Lisa, Blessing], [Arnold, Verdict]]

输出变量必须是类型:String[][]结果:

[0] => [Joey, Greek]
[1] => [Lisa, Blessing]
[2] => [Arnold, Verdict]

实现这一目标的最佳方法是什么?

标签: javaclassloader

解决方案


取决于输入的样子。最安全的方法可能是使用适当的解析器(也可能是不同的文件格式)。

如果列表始终采用格式[[Name], [Name]]并且Name从不包含括号,则一种简单的方法可能是使用更专业的正则表达式,例如(?<=\]),\s*(?=\[).

正则表达式的概要:

  • (?<=\]): 积极的后视,即任何匹配都必须跟在].
  • ,\s*:要拆分(和删除)的实际匹配项,即逗号后跟任何空格
  • (?=\[)"): 正向前瞻,即任何匹配必须后跟一个[.

最后,将每个名称拆分,为 2D 数组:

//results in Strings like "[Joey, Greek]", "[Lisa, Blessing]", and "[Arnold, Verdict]"
String[] completeNames = properties.getProperty("names").split("(?<=\\]),\\s*(?=\\[)");

//We're using a stream here but you could as well use traditional loops   
String[][] namesInParts = Arrays.stream(completeNames)
           //map the name by removing the brackets and splitting at the comma (followed by any whitespace)
           .map(name -> name.replaceAll("[\\]\\[]", "").split(",\\s*"))
           //collect everything into a new array
           .toArray(String[][]::new);

推荐阅读