How can I set same Value for multiple Keys in Java properties?

拜拜、爱过 提交于 2021-01-27 18:40:49

问题


I wish to achieve something like -

File.properties contains,

    prop1, prop2 = valueX
    prop3, prop4 = valueZ

where `props.getProperty("prop1");` should return `valueX`

I know one way is to write the same value again different keys but that makes my property file cluttered and does not provide an analytical view for the business purpose.

PS: If it is somehow possible then, please describe the case where the same key appears with different values.


回答1:


I wish to achieve something like

File.properties contains,

prop1, prop2 = valueX
prop3, prop4 = valueZ

where props.getProperty("prop1"); should return valueX

The documentation for the .properties file format and the DTD for the XML properties format both provide only for mapping a single key at a time to an associated literal value. These simple formats do not support what you describe. The only alternative they afford is to give a value for each key separately, duplicating values as needed.

that makes my property file cluttered and does not provide an analytical view for the business purpose.

I guess that's in the eye of the beholder. Personally, I think your variation is just the flip side of the same coin. Either way, it is unclear whether keys bearing identical values do so incidentally or because it is important that their values be the same. And as far as writing such files for human consumption, I prefer the keys to be separate, as that makes them easier to find, and better affords grouping and sorting them.

If it is somehow possible then, please describe the case where the same key appears with different values.

Huh? Each key should have exactly one value. It is not documented what should happen if the same key appears more than once.

Perhaps you mean the same value being assigned to different keys, but I don't understand why that's in any question. Nevertheless, here:

prop1 = valueX
prop2 = valueX
prop3 = valueZ
prop4 = valueZ

Note that the = symbols can be replaced with : or just whitespace if you prefer. If you don't like that then you can define your own format, and write your own code for parsing an instance into a Properties object.



来源:https://stackoverflow.com/questions/54914535/how-can-i-set-same-value-for-multiple-keys-in-java-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!