简体   繁体   中英

Placing a properties file in a java project

I am having some trouble understanding where to place a properties file in a java project. I have the following project structure .

src.
   |
    java
        |
         test.properties
                        |
                        a.java
                        Parameters.properties 

I have the following code to read the properties file .

 Properties prop = new Properties();


    try {
        InputStream in = this.getClass().getResourceAsStream("Parameters.properties");
       // load a properties file
        prop.load(in);
       // get the property value and print it out
        System.out.println(prop.getProperty("hello.world"));
    } catch (IOException ex) {
        ex.printStackTrace();
        System.out.println("The code has failed here");
    }

my properties file has the following line

hello.world=Hello World

I keep getting a null pointer error which leads me to believe it is not able to read the file because it has not got the file yet .

You need to put your file Parameters.properties not in src folder, but in built or target folder. Or for simple explanation find a.class file and put Parameters.properties in the same folder.

built.
   |
    java
        |
         test.properties
                        |
                        a.class
                        Parameters.properties 

Because when you use getClass() method you get binary file with .class extension and search resources in folder where this file is.

1.) One way of doing this is --- Add your properties file in any source folder. A source folder is a folder that is included in class path. eg src/ A.java Create another Source folder

at src level and place file here

resources/params.properties.

And in A.java acces like this File file = new File(".//resources//params.properties");

2.) Another easy way Add properties file in src folder, and Right click on properties file -> build Path ->Add to Class Path.

And Access file in A.java like this....

File file = new File("params.properties");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM