Load Properties File Classpath Java
If you want to read Properties file values using classpath then its mandatory to put property file in classpath otherwise you will get exception. If you keep your property file inside src folder then it will be available to the classpath. If your existing project structure have property file outside src folder then you will have to set path of the file in classpath.
- Sample Java project structure from where we will read JavaHonk.properties file and print all its key values.
- LoadPropertyFileJava.java
package com.javahonk; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.Properties; public class LoadPropertyFileJava { public static void main(String[] args) { try { Properties properties = new Properties(); InputStream in = LoadPropertyFileJava.class.getClassLoader().getResourceAsStream("JavaHonk.properties"); properties.load(in); in.close(); //Print all value from property file Enumeration<?> enumeration =properties.propertyNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); System.out.println("Key: "+key+" Value: "+properties.getProperty(key)); } } catch (IOException e) { e.printStackTrace(); } } }
- Output:
If your properties file is in maven project structure below:
- Tibco.properties
TIBCO_URL=tcp://Javahonk.com:8222
- Then you could read as below by LoadPropertiesAndReadValue.java:
package com.javahonk.messaging; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class LoadPropertiesAndReadValue { private static Map<String, String> propKeyValue = new HashMap<>(); public static void main(String[] args) { System.out.println("TIBCO URL: "+getPropKeyValue("TIBCO_URL")); } private static void getPropertyValue() { Properties properties = new Properties(); InputStream inputStream = null; try { inputStream = new FileInputStream("src/main/resources/Tibco.properties"); properties.load(inputStream); Enumeration<?> enumeration =properties.propertyNames(); while (enumeration.hasMoreElements()) { String keyVal = (String) enumeration.nextElement(); propKeyValue.put(keyVal, properties.getProperty(keyVal)); } } catch (IOException iOException) { iOException.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException iOException) { iOException.printStackTrace(); } } } } public static String getPropKeyValue(String key) { if (propKeyValue.get(key) == null) { getPropertyValue(); return propKeyValue.get(key); }else { return propKeyValue.get(key); } } }
- For details please read oracle documentation here