简体   繁体   中英

Reading Value from property file at runtime

I have a following function :

public void execute(Tuple input, BasicOutputCollector collector) {

    String term = input.getString(0);
    int year = input.getInteger(1);
    int month = input.getInteger(2);
    int day = input.getInteger(3);
    int hour = input.getInteger(4);
    int dayofyear = input.getInteger(5);
    int weekofyear = input.getInteger(6);
    int productcount = input.getInteger(7);

    /*
     * Inserting Values In Cassandra
     */

    String insertUpdateTable = "UPDATE TopQuery SET count = count + 1 "
            + "where term = \'" + term + "\' AND year = " + year
            + " AND month = " + month + " AND day = " + day
            + " AND hour = " + hour + " AND dayofyear = " + dayofyear
            + " AND weekofyear = " + weekofyear + " AND productcount = "
            + productcount + ";";

    session.executeAsync(insertUpdateTable);

}

Here i'll be getting all the values like term , year , month , day , hour , dayofyear , weekofyear and productcount at runtime and will insert it into Cassandra DB.

Since, this String is constant and doesn't change I want to separate it out and put it into properties file.

I have already put the table structure into properties file and fetching it from there.So that, In future if i need to change the table structure I don't have to edit the code , rather I can simply edit the properties file.

But,How to store the insertUpdateTable in properties file so that it reads the data at runtime and updates the DB ?

To read a property file you can use the Properties class.

The Properties class represents a persistent set of properties. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list is a string.

But I'm not sure if it's a good idea to put SQL (or other code) into a property file. There's no difference in editing a java or a property file to change the SQL. After all it's a code change which requires testing and deployment. In every non trivial project you want to automate this steps anyway (ant, maven, ...).

in xyz.properties put value like this

query = *************

Now Try this

getProperties(){
                Properties prop = new Properties();
                String propFileName = "xyz.properties";

                inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);

                prop.load(inputStream);
                String query= prop.getProperty("query");
              }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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