Java – Read a property file
CodeDevEnglish
Source to keep somewhere: read a property file in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | /*********************************************************/ /* 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:
Access with:
1 | String myValue = LoadProperties.getInstance().getProperty( "mykey" ); |
Leave a comment