JayC
JayC

Reputation: 2292

How can I read a application properties file by prefix?

I am trying to first print my application properties into java, then push it into a thymeleaf html page. Purpose: to allow users to edit the properties file using GET/POST. My current code will display the values key and values of the properties to the console if it is equal to something. How can I get it where it would only extract specific and multiple prefixes?

Code/Attempt

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

Example 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

To be able to just print all values of prefix and some.

Upvotes: 1

Views: 2931

Answers (1)

Strelok
Strelok

Reputation: 51441

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

Is this what you want? Just print keys that start with "prefix" or "some"?

Upvotes: 1

Related Questions