Hitesh Kumar
Hitesh Kumar

Reputation: 514

Property file is returning as null in Java

I am trying to read some property from the properties file, but my code is not reading the property file. The properties file is in some folder in my machine.

Here is my code:

public String getproperty(){

    String extension="";
    Properties  prop = new Properties ();
    String propname = "\\"+Any location in your machine+"\\fileExtension.properties";
    Logger.debug("ReadFiles", " ----Property file path---- "+ propname, null);
    ip = getClass().getClassLoader().getResourceAsStream(propname);
    Logger.debug("ReadFiles", " ----ip value ---- "+ip, null);
        try {
            if(ip != null){
                prop.load(ip);
                Logger.debug("ReadFiles", " ----Property file loaded---- ", null);
            }

            extension = prop.getProperty("fileExt");
            Logger.debug("ReadFiles", " ----Property =  " + extension, null);

        } catch (IOException e) {
            Logger.error("ReadFiles", " ----Error while loading property file---- ", null);
            e.printStackTrace();
        }
        finally{
            try {
                ip.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return extension;
}

I am creating a jar placing it in lib folder of server (installed in my machine) and placing the properties file in my machine and given the same path in code. I have tried with absolute path and without absolute path.

Upvotes: 2

Views: 2713

Answers (1)

Niklas Rosencrantz
Niklas Rosencrantz

Reputation: 26652

Please try this example that uses an absolute path to the properties file.

package com.company;

import java.io.*;
import java.util.Properties;

public class Main {

    public static void main(String[] args) {

        Properties prop = new Properties();
        InputStream input = null;

        try {
            input = new FileInputStream("/home/dac/gs-rest-service/javacode/src/main/java/com/company/config.properties");
            prop.load(input);
            String extension = prop.getProperty("fileExt");
            System.out.println("ReadFiles ----Property =  " + extension);

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}

Test

cat /home/dac/gs-rest-service/javacode/src/main/java/com/company/config.properties 
#Mon Dec 26 17:31:30 CET 2016
dbpassword=password
database=localhost
dbuser=foobar
fileExt=.xml⏎      

Run the program

ReadFiles ----Property =  .xml        

Upvotes: 1

Related Questions