140

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

Jesper
  • 202,709
  • 46
  • 318
  • 350
nikos
  • 2,893
  • 11
  • 30
  • 39

17 Answers17

100

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");
Jesper
  • 202,709
  • 46
  • 318
  • 350
Mark Elliot
  • 75,278
  • 22
  • 140
  • 160
  • my file hierarchy is: src -> myPackage -> myClass.java , myProp.properties. I did what you advised me but it still throws the same exception – nikos Nov 27 '11 at 13:03
  • `getResourceAsStream` searches for the file on the classpath. If your properties file is in the package directory of `myPackage`, then use `/myPackage/myProp.properties` as the path. – Jesper Nov 27 '11 at 13:06
  • 3
    @Mark Elliot what if I have a `conf` package to store all my configuration files and my file hierarchy is: `myproject ->src, conf, test` ,how am i gonna load the properties by adding a preceding slash? – Roger Ray Aug 03 '13 at 15:03
67


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();
}
mathk
  • 7,973
  • 6
  • 45
  • 74
Steven Gomez
  • 687
  • 5
  • 2
  • 3
    Don't forget to close the `Reader` in `prop.load(reader)`, according to the documentation: `The specified stream remains open after this method returns` – Evandro Silva Jul 16 '18 at 18:01
  • There are many methods in that link. Why did you choose the one with class loader? Are there any advantages or disadvantages of that method? – MasterJoe Sep 23 '20 at 04:30
29

You can use ResourceBundle class to read the properties file.

ResourceBundle rb = ResourceBundle.getBundle("myProp.properties");
Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
dku.rajkumar
  • 18,414
  • 7
  • 41
  • 58
20
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

tienya
  • 201
  • 2
  • 5
  • My use case is for Jenkins so it's nice to have a solution that doesn't rely upon a bunch of ClassPathLoader shenanigans. Thanks! – Kyle Pittman Nov 10 '21 at 17:29
8

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.

Mukus
  • 4,870
  • 2
  • 43
  • 56
8

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);
manikanta nvsr
  • 487
  • 5
  • 20
7

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

props.load(this.getClass().getResourceAsStream("myProps.properties"));
yegor256
  • 102,010
  • 123
  • 446
  • 597
6

if your config.properties is not in src/main/resource 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);
GUDDU KUMAR
  • 401
  • 4
  • 12
4

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);
Community
  • 1
  • 1
Oguzhan Cevik
  • 638
  • 8
  • 18
3

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

InputStream inputStream = getClass().getClassLoader().getResourceAsStream(myProps.properties); 
Tarun Jain
  • 262
  • 1
  • 8
  • How to convert InputStream to File in java? I wanted to read .properties file using File API –  Jan 10 '16 at 12:34
3

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.

VHS
  • 9,534
  • 3
  • 19
  • 43
3

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.

mort
  • 12,988
  • 14
  • 52
  • 97
  • my file hierarchy is: src -> myPackage -> myClass.java , myProp.properties. I did what you advised me but it still throws the same exception – nikos Nov 27 '11 at 13:01
  • Since your properties file is not at the root of your project, you don't need the leading slash. – mort Nov 27 '11 at 13:04
  • I was getting the exception thrown in the first place without the leading slash. It's still not working. – nikos Nov 27 '11 at 13:06
3

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")
Mercer
  • 9,736
  • 30
  • 105
  • 170
twr
  • 96
  • 3
2

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);
}
Luke Hutchison
  • 8,186
  • 2
  • 45
  • 40
2

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;
Lunatic
  • 1,519
  • 8
  • 24
1

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>");
    }
Walk
  • 1,531
  • 17
  • 21
-2

Specify the path starting from src as below:

src/main/resources/myprop.proper
Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28