简体   繁体   中英

How to call database.properties outside the project using notepad in java?

I want to take place database.properties outside the project, so when I want to change the content (database configuration) of that when I've build them into jar , I can do it easily without open my project again. So what to do?

First, place the database.properties file in the location you'd like it to be in.

Then, do one of the following:

  1. Add the directory where database.properties is located, to the classpath. Then use Thread.currentThread().getContextClassLoader().getResource() to get a URL to the file, or getResourceAsStream() to get an input stream for the file.
  2. If you don't mind your Java application knowing the exact location of the database.properties file, you can use simple File I/O to obtain a reference to the file (use new File(filename) ).

Usually, you'd want to stick with the first option. Place the file anywhere, and add the directory to the classpath. That way, your Java application doesn't have to be aware of the exact location of the file - it will find it as long as the file's directory is added to the runtime classpath.

Example (for the first approach):

public static void main(String []args) throws Exception {
    InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("database.properties");
    Properties props = new Properties();

    try {
        // Read the properties.
        props.load(stream);
    } finally {
        // Don't forget to close the stream, whatever happens.
        stream.close();
    }

    // When reaching this point, 'props' has your database properties.
}

Store properties file in your preferred location. Then do the following:

try {

    String myPropertiesFilePath = "D:\\configuration.properties"; // path to your properties file
    File myPropFile = new File(myPropertiesFilePath); // open the file

    Properties theConfiguration = new Properties();
    theConfiguration.load(new FileInputStream(myPropFile)); // load the properties

catch (Exception e) {

}

Now you can easily get properties as String from the file:

String datasourceContext = theConfiguration.getString("demo.datasource.context", "jdbc/demo-DS"); // second one is the default value, in case there is no property defined in the file

Your configuration.properties file might look something like this:

demo.datasource.context=jdbc/demo-DS
demo.datasource.password=123

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