繁体   English   中英

读取具有特定字符串的java中的属性文件

[英]Read properties file in java having particular string

我正在使用一个.properties文件。 在那我有以下配置参数:

Appnameweb = app1
Appnamemobile = app2
Appnameweb1 = app3

可以有许多以用户提供的Appname开头的配置参数。 如何读取所有属性文件参数,其中键将包含特定的字符串,如本例中的Appname?

一般来看看java.util.Properties javadoc。 为了让您的生活更轻松,我将为您提供此代码段,以帮助您开始:

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
    }
}
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));
    }   
}

如果你正在使用java Properties ,那么你可以做一些事情。

  1. 使用Properties#keySet()方法获取键的Set<Object>
  2. 启动for循环,对于键集中的每个对象,通过强制转换或使用toString()方法将Object转换为String
  3. 使用转换后的String,根据您的需要,使用String#contains()String#startsWith()方法检查它是否包含公共字符串“Appname”。
  4. 如果是,请使用Properties#getProperty()方法获取该键的值,并使用该值执行任何操作。
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("");
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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