Java Properties File Examples
1. Write to properties file
Set the property value, and write it into a properties file named “Data.properties“.
Navigation for creating the properties file:-
-> Right click on the package.
-> Go to “new”, Select the option “others”.
-> Expand “general”.
-> Select the option “file”.
-> Click on next.
-> Specify the desired file name with “.properties” extension, click on finish.
import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class App { public static void main( String[] args ) { Properties prop = new Properties(); try { //set the properties value prop.setProperty("database", "localhost"); prop.setProperty("dbuser", "mytest"); prop.setProperty("dbpassword", "password"); //save properties to project root folder prop.store(new FileOutputStream("Data.properties"), null); } catch (IOException ex) { ex.printStackTrace(); } } }
Output
Data.properties
dbpassword=password database=localhost dbuser=mytest
P.S If file path is not specified, then this properties file will be stored in your project root folder.
2. Load a properties file
Load a properties file from the file system and retrieved the property value.
import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class App { public static void main( String[] args ) { Properties prop = new Properties(); try { //load a properties file prop.load(new FileInputStream("Data.properties")); //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")); } catch (IOException ex) { ex.printStackTrace(); } } }
Output
localhost mytest password
3. Load a properties file from classpath
Load a properties file named “Data.properties” from project classpath, and retrieved the property value.
import java.io.FileInputStream; import java.io.IOException; import java.utilutil.Properties; public class App { public static void main( String[] args ) { Properties prop = new Properties(); try { //load a properties file from class path, inside static method prop.load(App.class.getClassLoader().getResourceAsStream("Data.properties");)); //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")); } catch (IOException ex) { ex.printStackTrace(); } } }
For non-static method, use this :
prop.load(getClass().getClassLoader().getResourceAsStream("Data.properties");));