Load property from properties file - Java java.util

Java examples for java.util:Properties File

Description

Load property from properties file

Demo Code


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

public class Main{
    public static void main(String[] argv) throws Exception{
        String file = "java2s.com";
        String property = "java2s.com";
        System.out.println(loadProperty(file,property));
    }/*from   w  ww  .jav  a  2 s .c o m*/
    /**
     * Carga un propiedad desde fichero de propiedades
     * Lanza runtime exception si no existe la propiedad o el fichero
     * 
     * @param file
     * @param property
     * @return
     */
    static String loadProperty(String file, String property) {

        Properties p = loadPropertiesFile(file);

        String value = p.getProperty(property);
        if (value == null) {
            throw new RuntimeException("Property not found in " + file);
        }
        return value;
    }
    private static Properties loadPropertiesFile(String file) {
        Properties p = new Properties();
        try {
            InputStream is = Factories.class.getResourceAsStream(file);

            p.load(is);

            is.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return p;
    }
}

Related Tutorials