如何通过前缀读取应用程序属性文件?

时间:2016-12-08 16:43:42

标签: java spring-boot thymeleaf

我想首先将我的应用程序属性打印到java中,然后将其推送到百万美元的html页面。目的:允许用户使用GET / POST编辑属性文件。我的当前代码将显示值键和属性值到控制台,如果它等于某事。我怎样才能获得它只提取特定和多个前缀的地方?

代码/尝试

public class ReadPropertiesFile {

    public static void readProp() {

        try {
            Properties prop = new Properties();
            prop.load(ReadPropertiesFile.class.getResourceAsStream("/application.properties"));

            Enumeration enuKeys = prop.keys();
            while (enuKeys.hasMoreElements()) {
                String key = (String) enuKeys.nextElement();
                String value = prop.getProperty(key);
                System.out.println(key + "= " + value);
            }
        } catch (FileNotFoundException e) {
            //System.out.print("System cannot find file");
            e.printStackTrace();
        } catch (IOException e) {
            //System.out.print("System cannot find file");
            e.printStackTrace();
        }
    }
}

示例application.properties

prefix.foo = bar@!car@!war@!scar
prefix.cool = honda@!toyota@lexus
some.feed = live@!stream@!offline
some.feed = humans@!dogs@!cat
noprefix = dont@!print@!me
host = host1@!host2@!host3

能够只打印前缀和某些值的所有值。

1 个答案:

答案 0 :(得分:1)

public class ReadPropertiesFile {


public static void readProp() {

 try {
    Properties prop = new Properties();
    prop.load(ReadPropertiesFile.class.getResourceAsStream("/application.properties"));

    Enumeration enuKeys = prop.keys();
        while (enuKeys.hasMoreElements()) {
                String key = (String) enuKeys.nextElement();
                String value = prop.getProperty(key);
                if (key.startsWith("prefix") || key.startsWith("some")) {
                    System.out.println(key + "= " + value);
                }
            }
            } catch (FileNotFoundException e) {
            //System.out.print("System cannot find file");
                e.printStackTrace();
            } catch (IOException e) {
                //System.out.print("System cannot find file");
                e.printStackTrace();
            }
}
这是你想要的吗?只需打印以"前缀"开头的键。或者"一些"?