读取具有特定字符串的 java 中的属性文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23510375/
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
Read properties file in java having particular string
提问by iRunner
I am using one .properties
file. In that I have following config parameters :
我正在使用一个.properties
文件。因为我有以下配置参数:
Appnameweb = app1
Appnamemobile = app2
Appnameweb1 = app3
There can be many config param starting with Appname provided by user. How to read all properties file parameters in which key will contain particular String like in this case Appname?
可以有许多以用户提供的 Appname 开头的配置参数。如何读取其中键将包含特定字符串的所有属性文件参数,如本例中的 Appname?
采纳答案by AlexR
Generally take a look on javadoc of java.util.Properties
. To make you life easier I will give you this code snippet that can help you to start:
一般看看 .javadoc 的java.util.Properties
。为了让你的生活更轻松,我会给你这个代码片段,可以帮助你开始:
Properties props = new Properties();
props.load(new FileInputStream("myfile.properties"));
for (Enumeration<?> e = props.propertyNames(); e.hasMoreElements(); ) {
String name = (String)e.nextElement();
String value = props.getProperty(name);
// now you have name and value
if (name.startsWith("Appname")) {
// this is the app name. Write yor code here
}
}
回答by aviad
Properties props = new Properties();
props.load(new FileInputStream("file.properties"));
Enumeration<String> e = props.getNames();
List<String> values = new ArrayList<String>();
while(e.hasMoreElements()) {
String param = (String) e.nextElement();
if(param != null && param.contains("Appname")) {
values.add(props.getProperty(param));
}
}
回答by SudoRahul
If you're using java Properties
, then you can do something on the lines of this.
如果您使用的是 java Properties
,那么您可以在此方面做一些事情。
- Get the
Set<Object>
of keys using theProperties#keySet()
method. - Start a
for
loop and for each object in the key set, convert theObject
toString
either by a cast or using thetoString()
method. - With the converted String, check if it contains the common string "Appname" using the
String#contains()
orString#startsWith()
method depending on your needs. - If it does, get the value for that key using the
Properties#getProperty()
method and do whatever you want with the value.
Set<Object>
使用该Properties#keySet()
方法获取密钥。- 开始一个
for
循环,并在关键组中的每个对象,转换Object
到String
要么通过流延或使用toString()
方法。 - 使用转换后的字符串,根据您的需要使用
String#contains()
或String#startsWith()
方法检查它是否包含公共字符串“Appname” 。 - 如果是,请使用该
Properties#getProperty()
方法获取该键的值并对该值执行任何您想要的操作。
回答by Sarang.C
Properties prop = new Properties();
try {
prop.load(this.getClass().getClassLoader().getResourceAsStream("filename.properties"));
Set<Object> set = prop.keySet();
for(Object obj : set){
String str = obj.toString();
if(str.startsWith("Appname")) {
//System.out.println("");
}
}