简体   繁体   中英

Add existing key as value to a new key in a java property file

I am using a properties file in my java project for storing the path of various resources. Ex :- Here is my properties file :-

MACHINE_NAME = "//pranay"
Json_path1 = MACHINE_NAME//Json//j1.txt
Json_path2 = MACHINE_NAME//Json//j2.txt

The value of key MACHINE_NAME is not getting replaced with its value ie pranay in another keys such as Json_path1 and Json_path2. Therefore i am unable to get the correct path. How to give the key MACHINE_NAME so that its value gets replaced in the other key values.

You can't do this automatically - it's simply not a feature of Java property files. You'll need to write code to do this wherever you plan to load/use the properties file.

You should think about:

  • whether you want to make this more explicit, eg using ${MACHINE_NAME} instead of just MACHINE_NAME
  • whether you have a fixed list of replacements you want to support, or whether you want to pick up anything that looks like it's a replacement (much easier if you have a syntax such as ${...} of course)
  • whether replacements can be recursive, eg MACHINE_NAME = ${USER_NAME}-laptop - and how to handle cycles if so

Standard Properties mechanism cannot handle this, but there are extensions. Try to look at eproperties . In other case do the substitutions yourself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM