Java – Read a property file
CodeDevEnglish
Source to keep somewhere: read a property file in Java:
/*********************************************************/ /* Récuperer un fichier properties */ /*********************************************************/ import java.io.InputStream; import java.util.Properties; public class LoadProperties { private static Properties props = null; private static final String PROPERTY_FILE = "com/mytests/ejb/client/agent.properties"; // Singleton private static LoadProperties instance = new LoadProperties(); public static LoadProperties getInstance() { return instance; } private LoadProperties() { this.init(); } private void init() { // If property isn't loaded if (props == null) { try { InputStream is = LoadProperties.class.getResourceAsStream(PROPERTY_FILE); if (is == null) { throw new Exception(); } props = new Properties(); props.load(is); } catch (Exception e) { System.out.println("Could not load property file!"); } } } public String getProperty(String key) { return props.getProperty(key); } }
Example of property file:
1 2 |
mykey = myvalue com.toto.security.aloha = another value like this |
Access with:
String myValue = LoadProperties.getInstance().getProperty("mykey");