nikos
nikos

Reputation: 3013

Reading Properties file in Java

I have the following code trying to read a .properties file:

Properties prop = new Properties();
ClassLoader loader = Thread.currentThread().getContextClassLoader();           
InputStream stream = loader.getResourceAsStream("myProp.properties");
prop.load(stream);

I get an exception at the last line. Specifically:

Exception in thread "main" java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:418)
at java.util.Properties.load0(Properties.java:337)
at java.util.Properties.load(Properties.java:325)
at Assignment1.BaseStation.readPropertyFile(BaseStation.java:46)
at Assignment1.BaseStation.main(BaseStation.java:87)

thanks, Nikos

Upvotes: 148

Views: 550426

Answers (17)

Oguzhan Cevik
Oguzhan Cevik

Reputation: 686

If your .properties file path and your Java class path are same then you should this:

For example:

src/myPackage/MyClass.java

src/myPackage/MyFile.properties

Properties prop = new Properties();
InputStream stream = MyClass.class.getResourceAsStream("MyFile.properties");
prop.load(stream);

Upvotes: 4

GUDDU KUMAR
GUDDU KUMAR

Reputation: 401

If your config.properties is not in src/main/resources directory and it is in root directory of the project then you need to do somethinglike below :-

Properties prop = new Properties();          
File configFile = new File(myProp.properties);
InputStream stream = new FileInputStream(configFile);
prop.load(stream);

Upvotes: 6

manikanta nvsr
manikanta nvsr

Reputation: 577

I see that the question is an old one. If anyone stumbles upon this in the future, I think this is one simple way of doing it. Keep the .properties file in your project folder.

FileReader reader = new FileReader("Config.properties");
Properties prop = new Properties();
prop.load(reader);

Upvotes: 10

Lunatic
Lunatic

Reputation: 1926

A good practice which is not state in previous solution is to passing properties especially the property files that generated in compile time with build plugins perhaps, is to Use PropertySourcesPlaceholderConfigurer

    @Bean
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
        PropertySourcesPlaceholderConfigurer propsConfig 
          = new PropertySourcesPlaceholderConfigurer();
        propsConfig.setLocation(new ClassPathResource("myProp.properties"));
        propsConfig.setIgnoreResourceNotFound(true);
        propsConfig.setIgnoreUnresolvablePlaceholders(true);
        return propsConfig;
    }

then can accessing the properties from IOC as demand such

    @Value("${your.desired.property.pointer}")
    private String value;

Upvotes: 2

Luke Hutchison
Luke Hutchison

Reputation: 9230

None of the current answers show the InputStream being closed (this will leak a file descriptor), and/or don't deal with .getResourceAsStream() returning null when the resource is not found (this will lead to a NullPointerException with the confusing message, "inStream parameter is null"). You need something like the following:

String propertiesFilename = "server.properties";
Properties prop = new Properties();
try (var inputStream = getClass().getClassLoader().getResourceAsStream(propertiesFilename)) {
    if (inputStream == null) {
        throw new FileNotFoundException(propertiesFilename);
    }
    prop.load(inputStream);
} catch (IOException e) {
    throw new RuntimeException(
                "Could not read " + propertiesFilename + " resource file: " + e);
}

Upvotes: 4

user11159629
user11159629

Reputation: 9

Specify the path starting from src as below:

src/main/resources/myprop.proper

Upvotes: -2

VHS
VHS

Reputation: 10184

Many answers here describe dangerous methods where they instantiate a file input stream but do not get a reference to the input stream in order to close the stream later. This results in dangling input streams and memory leaks. The correct way of loading the properties should be similar to following:

    Properties prop = new Properties();
    try(InputStream fis = new FileInputStream("myProp.properties")) {
        prop.load(fis);
    }
    catch(Exception e) {
        System.out.println("Unable to find the specified properties file");
        e.printStackTrace();
        return;
    }

Note the instantiating of the file input stream in try-with-resources block. Since a FileInputStream is autocloseable, it will be automatically closed after the try-with-resources block is exited. If you want to use a simple try block, you must explicitly close it using fis.close(); in the finally block.

Upvotes: 5

Walk
Walk

Reputation: 1649

For Reading Properties file with its original order:

    File file = new File("../config/edc.properties");
    PropertiesConfiguration config = new PropertiesConfiguration();
    PropertiesConfigurationLayout layout = new PropertiesConfigurationLayout(config);
    layout.load(new InputStreamReader(new FileInputStream(file)));

    for(Object propKey : layout.getKeys()){
        PropertiesConfiguration propval =  layout.getConfiguration();
        String value = propval.getProperty((String) propKey).toString();
        out.print("Current Key:" + propkey + "Current Value:" + propval + "<br>");
    }

Upvotes: 1

twr
twr

Reputation: 96

Given the context loader.getResourceAsStream("myPackage/myProp.properties") should be used.

Leading '/' doesn't work with ClassLoader.getResourceAsStream(String) method.

Alternatively you could use Class.getResourceAsStream(String) method, which uses '/' to determine if the path is absolute or relative to the class location.

Examples:

myClass.class.getResourceAsStream("myProp.properties")
myClass.class.getResourceAsStream("/myPackage/myProp.properties")

Upvotes: 3

tienya
tienya

Reputation: 271

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

Upvotes: 27

Mukus
Mukus

Reputation: 5033

You can't use this keyword like -

props.load(this.getClass().getResourceAsStream("myProps.properties"));

in a static context.

The best thing would be to get hold of application context like -

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:/META-INF/spring/app-context.xml");

then you can load the resource file from the classpath -

//load a properties file from class path, inside static method
        prop.load(context.getClassLoader().getResourceAsStream("config.properties"));

This will work for both static and non static context and the best part is this properties file can be in any package/folder included in the application's classpath.

Upvotes: 8

dku.rajkumar
dku.rajkumar

Reputation: 18588

You can use ResourceBundle class to read the properties file.

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

Upvotes: 31

Tarun Jain
Tarun Jain

Reputation: 272

You can use java.io.InputStream to read the file as shown below:

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(myProps.properties); 

Upvotes: 3

Steven Gomez
Steven Gomez

Reputation: 727


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();
}

Upvotes: 71

Mark Elliot
Mark Elliot

Reputation: 77094

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");

Upvotes: 105

yegor256
yegor256

Reputation: 105193

Your file should be available as com/example/foo/myProps.properties in classpath. Then load it as:

props.load(this.getClass().getResourceAsStream("myProps.properties"));

Upvotes: 7

mort
mort

Reputation: 13598

Make sure that the file name is correct and that the file is actually in the class path. getResourceAsStream() will return null if this is not the case which causes the last line to throw the exception.

If myProp.properties is in the root directory of your project, use /myProp.properties instead.

Upvotes: 3

Related Questions