Read properties file

Setup

Constants

private static final Logger logger = Logger.getLogger(ReadPropertiesFile.class);
private static final String PROPERTY_FILE_NAME = "com/levelup/java/util/read.properties";

Read.properties

website=http://www.leveluplunch.com
language=English
message=Welcome up to leveluplunch.com

Straight up Java

@Test
public void read_properties_file_java() throws FileNotFoundException,
        IOException {

    Properties properties = new Properties();
    properties.load(this.getClass().getClassLoader().getResourceAsStream(PROPERTY_FILE_NAME));
    
    logger.info(properties);
    
    assertEquals("http://www.leveluplunch.com", properties.getProperty("website"));
    assertEquals("English", properties.getProperty("language"));
    assertEquals("Welcome up to leveluplunch.com", properties.getProperty("message"));
}

Google Guava

    
@Test
public void read_properties_file_guava() throws IOException {
    
    URL url = Resources.getResource(PROPERTY_FILE_NAME);
    InputSupplier<InputStream> inputSupplier = 
            Resources.newInputStreamSupplier(url);
    
    Properties properties = new Properties();
    properties.load(inputSupplier.getInput());
    
    logger.info(properties);
    
    assertEquals("http://www.leveluplunch.com", properties.getProperty("website"));
    assertEquals("English", properties.getProperty("language"));
    assertEquals("Welcome up to leveluplunch.com", properties.getProperty("message"));
}

Apache Commons

@Test
public void read_properties_file_apache_commons () throws ConfigurationException {

    PropertiesConfiguration properties = new PropertiesConfiguration(PROPERTY_FILE_NAME);
    
    logger.info(properties);
    
    assertEquals("http://www.leveluplunch.com", properties.getProperty("website"));
    assertEquals("English", properties.getProperty("language"));
    assertEquals("Welcome up to leveluplunch.com", properties.getProperty("message"));
}

Spring Framework

/**
 * This is just one way to get properties in the springframework and 
 * could be based on environment, xml configuration, java config, etc.
 *      
 * @see PropertyPlaceholderConfigurer
 * @see PropertySourcesPlaceholderConfigurer
 * @throws IOException
 */
@Test
public void read_properties_file_springframework () throws IOException {

    Resource resource = new ClassPathResource(PROPERTY_FILE_NAME);
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);

    logger.info(properties);
    
    assertEquals("http://www.leveluplunch.com", properties.getProperty("website"));
    assertEquals("English", properties.getProperty("language"));
    assertEquals("Welcome up to leveluplunch.com", properties.getProperty("message"));
}