Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading Properties file in Java

People also ask

How read properties file line by line in Java?

Java Read File line by line using BufferedReader We can use java.io.BufferedReader readLine() method to read file line by line to String. This method returns null when end of file is reached. Below is a simple program showing example for java read file line by line using BufferedReader.

How do I load a properties file?

The Properties file can be used in Java to externalize the configuration and to store the key-value pairs. The Properties. load() method of Properties class is convenient to load . properties file in the form of key-value pairs.


Based on your exception, the InputStream is null, this means the class loader is not finding your properties file. I'm guessing that myProp.properties is in the root of your project, if that's the case, you need a preceding slash:

InputStream stream = loader.getResourceAsStream("/myProp.properties");


You can find information on this page:
http://www.mkyong.com/java/java-properties-file-examples/

Properties prop = new Properties();
try {
    //load a properties file from class path, inside static method
    prop.load(App.class.getClassLoader().getResourceAsStream("config.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();
}

You can use ResourceBundle class to read the properties file.

ResourceBundle rb = ResourceBundle.getBundle("myProp.properties");

Properties prop = new Properties();

try {
    prop.load(new FileInputStream("conf/filename.properties"));
} catch (IOException e) {
    e.printStackTrace();
}

conf/filename.properties base on project root dir