Reads a property value identified by key from the given property File. - Java java.util

Java examples for java.util:Properties File

Description

Reads a property value identified by key from the given property File.

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.util.Properties;

public class Main {
    /**// w w  w. j  av  a2 s  . c  o m
     * Reads a property value identified by key from the given property File.
     * @param propertyFile
     * @param key
     * @return the value of the given key
     */
    public static String loadProperty(String propertyFile, String key) {

        if (key == null)
            return null;

        try {
            FileInputStream in = null;
            File file = new File(propertyFile);

            //Return default if metadata not found
            if (!file.exists()) {
                return null;
            }
            //Read in metadata
            Properties prop = new Properties();
            in = new FileInputStream(file.getAbsolutePath());
            prop.load(in);
            in.close();

            //If data is not found, return default
            if (prop.getProperty(key) != null)
                return prop.getProperty(key);

        } catch (IOException e) {
            e.printStackTrace(System.err);
        } catch (NumberFormatException e) {
            e.printStackTrace(System.err);
        }
        //If exception is thrown, return default
        return null;
    }
}

Related Tutorials