验证Java8中属性文件中键的最佳方法

时间:2019-04-04 06:59:21

标签: java

我有一个属性文件,需要针对一组键和值进行验证。 这样用户就不能在属性文件中提供任何匿名密钥或无效值。

我通过读取属性文件并创建所有可能键的ENUM来完成此操作,并且借助流,我使用Enum中提到的方法验证了属性文件中的每个键。

我的枚举:

public enum VersionEnum {
A,
B,
C,
D

public static Stream<VersionEnum> stream() {
        return Arrays.stream(VersionEnum.values());
    }
}

然后运行另一个循环以比较每个键的值。

我想知道是否有更好的方法可以在Java中完成此操作?

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

Imho,更好方法(因为没有一个 best 存在)正在维护存储在另一个文件中的 default 属性集。对于这种任务,使用硬编码的Enum听起来太“奇怪”。

查看带有注释的示例代码(如果您不喜欢阅读,请下移Stream解决方案)。
对于键,我们可以使用Properties#keySet()

// Load default/allowed properties from a resource file
final Properties allowed = new Properties();
properties.load(allowedInput);

// Load user-defined properties from a file
final Properties userDefined = new Properties();
properties.load(userDefinedInput);

// Remove all the keys from the user-defined Property
// that match with the allowed one. 
final Collection<Object> userDefinedCopy = new HashSet<>(userDefined.keySet());
userDefinedCopy.removeAll(allowed.keySet());

// If the key Set is not empty, it means the user added
// invalid or not allowed keys
if (!userDefined.isEmpty()) {
    // Error!
}

如果顺序或与键的关联不重要,则对Properties#values()的值也可以采用相同的方法。

final Collection<Object> allowedValues = allowed.values();
final Collection<Object> userDefinedValues = userDefined.values();
userDefinedValues.removeAll(allowedValues);

if (!userDefinedValues.isEmpty()) {
    // Error!
}

在这种情况下,我们不需要创建其他Collection<T>,因为Properties正在为我们做

@Override
public Collection<Object> values() {
    return Collections.synchronizedCollection(map.values(), this);
}

如果键值关联很重要,甚至是Stream解决方案

final Properties allowed = new Properties();
// Load

final Properties userDefined = new Properties();
// Load

final long count =
    userDefined.entrySet()
               .stream()
               .filter(e -> {
                  final Object o = allowed.get(e.getKey());

                  // If 'o' is null, the user-defined property is out of bounds.
                  // If 'o' is present ('o' represents the valid value), but it doesn't
                  // match with the user-defined value, the property is wrong

                  return o == null || !Objects.equals(o, e.getValue());
               }).count();

if (count != 0) {
   // Error!
}

您可以在Ideone.com here上玩它。