coure2011
coure2011

Reputation: 42394

Properties file not found - how to locate it as resource?

I have a properties file at location (from netbeans project explorer)

-MyTest
    +Web Pages
    +Source Packages
    -Test Packages
        -<default package>
            +Env.properties     <---- Here it is
        +com.mycomp.gts.test
        +com.mycomp.gts.logintest
        .....
        ....

Now when I am trying to find this file using code

InputStream propertiesInputStream = getClass().getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);

Its throwing java.lang.NullPointerException

Upvotes: 2

Views: 23310

Answers (4)

Rcousins89
Rcousins89

Reputation: 1

The below code reads a property file stored within the resources folder of a Maven project.

InputStream inputStream = YourClass.class.getResourceAsStream("/filename.properties");
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
    
Properties properties = new Properties();
properties.load(reader);
  
} catch (IOException ioException) {
    ioException.printStackTrace();
}

Upvotes: 0

sk2212
sk2212

Reputation: 1722

Try to get absolute path with:

String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();

You can print out the string absolute and try to substring it to your path of your properties file.

Upvotes: 1

Hunter Zhao
Hunter Zhao

Reputation: 4649

String basePath = PropertiesUtil.class.getResource("/").getPath();
InputStream in = new FileInputStream(basePath + "Env.properties");
pros.load(in);

Good luck:)

Upvotes: 1

Perception
Perception

Reputation: 80593

You cannot use the class as a reference to load the resource, because the resource path is not relative to the class. Use the class loader instead:

InputStream propertiesInputStream = getClass().getClassLoader()
        .getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);

Or alternatively, you can use the context class loader of the current thread:

InputStream propertiesInputStream = Thread.currentThread()
    .getContextClassLoader().getResourceAsStream("Env.properties");
ENV.load(propertiesInputStream);

Upvotes: 7

Related Questions