Java 我可以在属性文件中引用另一个属性吗(使用 ${property})

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1412132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:48:46  来源:igfitidea点击:

Can I reference another property in a properties file (use ${property})

javapropertiesparametersinclude

提问by Martin Magakian

Possible Duplicate:
How to reference another property in java.util.Properties?

可能的重复:
如何在 java.util.Properties 中引用另一个属性?

look at my "file.properties":

看看我的“file.properties”:

key1= My name is
key2= ${key1} Martin !


Why when I get the value of "key2" my result is "${key1} Martin !" unlike "My name is Martin !"

为什么当我得到“key2”的值时,结果是“${key1} Martin!” 不像“我叫马丁!”

=> I program in Java 6
=> I use java.util.Properties

=> 我用 Java 6 编程
=> 我使用 java.util.Properties

采纳答案by ZZ Coder

You might want look at Apache Configuration,

你可能想看看 Apache 配置,

http://commons.apache.org/configuration/

http://commons.apache.org/configuration/

Among many features it supports is the Variable Interpolation.

它支持的许多功能包括变量插值

回答by Thomas Owens

What you want to do is impossible using the Java Propertiesclass.

使用 JavaProperties无法实现您想要做的事情。

Property keys and values are simply Strings. No processing happens to them, so you can't refer to another value in a value.

属性键和值只是字符串。它们不会发生任何处理,因此您不能在一个值中引用另一个值。

回答by McDowell

Ant files are scripts; properties files are buckets of strings.

Ant 文件是脚本;属性文件是字符串桶。

The primary purpose of properties files is to serve as string containers for translatable text. The format strings typically used in resource bundles use an index-based system. When the string is translated, the order of the parameters can be changed in translated versions of the string without needing to change the Java code.

属性文件的主要目的是作为可翻译文本的字符串容器。资源包中通常使用的格式字符串使用基于索引的系统。翻译字符串时,可以在字符串的翻译版本中更改参数的顺序,而无需更改 Java 代码。

String what = "Hello";
String who = "Martin";
System.out.println(MessageFormat.format("{0}, {1}!", what, who));
System.out.println(MessageFormat.format("{1}, {0}!", what, who));

Output:

输出:

Hello, Martin!
Martin, Hello!

For use cases like this, it would not make sense to encapsulate the functionality in the Properties class because the strings usually need data from the application. The MessageFormatclass can be used to perform the substitution.

对于此类用例,将功能封装在 Properties 类中是没有意义的,因为字符串通常需要来自应用程序的数据。所述的MessageFormat类可以被用来执行替换。

This type of formatting should not be confused with the otherformatting options as specified by Formatter:

这种类型的格式不应与Formatter指定的其他格式选项混淆:

System.out.format("%s, %s!%n", what, who);