对于由特性文件控制的循环迭代



我有一个包含method的应用程序,该应用程序用于使用For-Loop:循环通过Hash Map

public void iterateHashMap(Map<Dog, List<String>> mapOfDogsAndDescriptions){
        for (Map.Entry<Dog, List<String>> entry : mapOfDogIdsAndStrings.entrySet()) {
            String key = entry.getKey().getId();
            List<String> StringList = entry.getValue();
            //do something
            }
    }

我希望能够根据properties文件中的属性定义循环迭代的次数。

例如,如果属性设置为3,则它只遍历Hash Map中的前3个键。

这是我第一次在Java应用程序中使用properties file,我该怎么做?

我会这样做:

public void iterateHashMap(Map<Dog, List<String>> mapOfDogsAndDescriptions){
    int count = Integer.parseInt(System.getProperty("count"));
    for (Map.Entry<Dog, List<String>> entry : mapOfDogIdsAndStrings.entrySet()) {
        if (count-- <= 0)
            break;
        String key = entry.getKey().getId();
        List<String> StringList = entry.getValue();
        //do something
    }
}

在纯java中,您可以执行

Properties prop = new Properties();
String propFileName = "config.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
    prop.load(inputStream);
} else {
    throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
int cpt  = Integer.valueOf(prop.getProperty("counter"));
int cptLoop = 0;
for (Map.Entry<Dog, List<String>> entry : mapOfDogIdsAndStrings.entrySet()) {
    if (cptLoop == cpt)
        break;
    String key = entry.getKey().getId();
    List<String> StringList = entry.getValue();
    //do something
    cptLoop++;
}

您在使用任何框架吗?在Spring Framework中,您可以这样做:

@Resource(name = "properties")
private Properties properties;

在您的应用程序中上下文:

<bean id="properties"
      class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="location" value="classpath:urls.properties"></property>
</bean>

最后,在您的方法中:

int counter = 0;
Integer limit = Integer.parseInt(properties.getProperty("some property"));
for(//Some conditions){
    //Some code
    counter++;
    if(counter > limit) break;
}

最新更新