The log4j.properties file is a log4j configuration file. Advantage of using log4j.properties file is that, if we make any change in java file we have to recompile it. But if we make any change in log4j.properties file then there is no need to compile.
Log4j.properties file keeps properties in key-value pairs. By default, the LogManager looks for a file named log4j.properties in the CLASSPATH.
Project structure
App.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 46 47 | package readPropertiesFile; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; //Java Properties File Example // .ini or .properties file have same functionalities, only extension is different // For these properties files to be read, it should be pasted directly in main project folder public class App { public static void main(String[] args) { Properties prop = new Properties(); InputStream readIni = null; InputStream readProperties = null; try { readIni = new FileInputStream("config.ini"); readProperties = new FileInputStream("config.properties"); // load .ini file prop.load(readIni); // get the property value and print it out System.out.println(prop.getProperty("database")); System.out.println(prop.getProperty("dbuser")); System.out.println(prop.getProperty("dbpassword")); // load .properties file prop.load(readProperties); String dbname=prop.getProperty("database"); // store in variable System.out.println("------dbname------"+dbname); System.out.println(prop.getProperty("database")); System.out.println(prop.getProperty("dbuser")); System.out.println(prop.getProperty("dbpassword")); } catch (IOException ex) { ex.printStackTrace(); } } } |
config.ini
1 2 3 4 | #Fri Jan 17 22:37:45 MYT 2014 dbpassword=password_ini database=localhost_ini dbuser=mkyong_ini |
config.properties
1 2 3 4 | #Fri Jan 17 22:37:45 MYT 2014 dbpassword=password_properties database=localhost_properties dbuser=mkyong_properties |
Output:
localhost_ini
mkyong_ini
password_ini
------dbname------localhost_properties
localhost_properties
mkyong_properties
password_properties
No comments :
Post a Comment