简体   繁体   中英

How to read from properties file?

I want to read a line from properties file called jdbc.properties. It locate in src\\main\\webapp\\WEB-INF\\db\\jdbc.properties . What path should I use? This is my method:

Properties prop = new Properties();

        try {
            // load a properties file
            prop.load(new FileInputStream("jdbc.properties"));

            System.out.println(prop.getProperty("password"));

        } catch (IOException ex) {
            ex.printStackTrace();
        }

If you move your properties file to src/main/resources , assuming your project is managed by maven, then you could retrieve it by doing

Properties prop = new Properties();

try {
    // load a properties file
    prop.load(YourClass.class.getResourceAsStream("/jdbc.properties")); // note the leading /

    System.out.println(prop.getProperty("password"));

} catch (IOException ex) {
    ex.printStackTrace();
}

where YourClass is whatever class this code is in.

Maven places the class files of your compiled classes and all resources in src/main/resources in WEB-INF/classes where only your application can access them.

If you put the file in src/main/resources/someFolder , you'll need to access it from

prop.load(YourClass.class.getResourceAsStream("/someFolder/jdbcProperties"));

The path you provide to the above method is relative to the package of the class you are in, unless you specify a leading forward-slash, in which case it will be relative to the root of the classpath, ie classes folder.

You need to specify an absolute path to the FileInputStream . You can get the path by calling servletContext.getRealPath("/WEB-INF/db/jdbc.properties")

If you do not have the servletContext available (via .getServletContext() ), then you should pass it (or the absolute path to the root of the app) to the code above.

Is environment variable set for TOMCAT_HOME, if not set it up.

Now you can use

<tomcat_home>/webapps/<yourapp>/web-inf/db/jdbc.properties

To get value of environment variable use following code:

Map<String, String> env = System.getenv();

Cheers !!

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