.:: CODE SNIPPET ::.

"Your time is limited, so don't waste it living someone else's life"

Basically usage of properties file in Java project


Properties file is just a file whose extension is properties in a Java project. It simply contains the pair of key-value string separated by a equal character. Properties file is used for obtaining configuration information, interface messages,…for usual. In generally, it is used for some circumstances in which we need to change the information easily. What functions does Java suppose us to do with a properties files? They comprise loading all information stored in properties file and listing them, retrieving any key-value pair, updating the value of a pair. These actions are all via a Properties object. The following snippets depict the functions:
Getting a value from a key:

/** The prop. */
    private static Properties prop = null;

    static
    {
        InputStream is = null;
        try
        {
            is = new FileInputStream(PropertiesUtil.class.getResource("")
                .getPath() + "config.properties");
            prop = new Properties();
            prop.load(is);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Gets the string.
     *
     * @param keyString the attribute
     * @return the string
     */
    public static String getString(final String keyString)
    {
        return prop.getProperty(keyString);
    }

Updating a value: by adding into above class with a method

/**
     * Sets the string.
     *
     * @param keyString the attribute
     * @return the string
     */
    public static String setString(final String keyString, final String valueString)
    {
        return prop.setProperty(keyString, valueString);
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: