如何按原始顺序读取java中的属性文件
我需要读取属性文件并在 Java 中生成一个 Properties 类。我这样做是通过使用:
Properties props = new Properties();
props.load(new FileInputStream(args[0]));
for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
}
但是,props.propertyName 返回的属性不按原始属性文件的顺序排列。据我所知,属性只是老式的、非泛化的哈希表。我正在寻找解决方法。有什么想法吗?谢谢你!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
示例来自 www.java2s.com 应该可以解决您的问题。
您的代码将更改为:
Example from www.java2s.com should solve your problem.
And your code will change to:
您可以扩展 Properties 并将所有映射方法委托给 LinkedHashMap< /a> 保留顺序。这是一个示例(您可能需要重写更多方法):
You can extend Properties and delegate all map methods to a LinkedHashMap to retain the order. Here is an example (you may need to override some more methods):
与上述之一类似,但没有维护我们自己的值列表的开销。我们所要做的就是维护一个单独的有序键列表,并提供一个新的“keys()”方法。
Similar to one of the above, but w/out the overhead of maintaining our own list of values. All we have to do is maintain a separate ordered list of the keys, and provide a new "keys()" method.
您可能想实现自己的具有类似功能的 Properties 类。
您将无法获取订单,因为正如您已经指出的那样,它使用
Hashtable
。You may want to implement your own Properties class with similar functionalities.
It will not be possible for you to obtain the order since, as you already pointed out, it uses
Hashtable
.基于LinkedHashMap的完整实现
结果:
full implementation based on LinkedHashMap
Result:
事实上,它们在底层被表示为
Hashtable
,这意味着它们的顺序不以任何方式保存。如果您绝对渴望此功能,我建议您“推出自己的”属性阅读器。
The fact they are represented as a
Hashtable
under the hood means that their order is not kept in any fashion.I'd suggest you "roll your own" properties reader if you're absolutely desperate for this functionality.
keySet 的正确实现:
Proper implementation of keySet:
子类属性以记住阅读顺序并创建使用有序键列表的枚举?
Subclass Properties to memorize reading order and create an Enumeration that uses the ordered keys list ?
解决问题:“根据属性文件中的顺序执行类”。我通常使用两种可能性之一:
1 - 使用一个属性作为逗号分隔的列表,包含类名或类定义的键
或(如果“定义”由多个属性组成,则很有用)
2 - 使用键后跟索引(计数器)。循环读取键,直到找不到值。
To solve the problem: "to execute classes based on the order in the properties file." I normally used one of 2 possibilities:
1 - use one property as a comma-separated list with the class-names or with the keys to the class definition
or (useful if the "definition" consists of more than one property)
2 - use a key followed by an index (counter). Read the keys in a loop until no value is found.