0

我想在项目之外进行 database.properties,所以当我想在构建它们时更改其内容(数据库配置)时jar,我可以轻松地完成它而无需再次打开我的项目。那么该怎么办?

4

2 回答 2

0

首先,将database.properties文件放在您想要的位置。

然后,执行以下操作之一:

  1. 将所在的目录添加database.properties到类路径中。然后用于Thread.currentThread().getContextClassLoader().getResource()获取文件的 URL,或getResourceAsStream()获取文件的输入流。
  2. 如果您不介意 Java 应用程序知道文件的确切位置,则database.properties可以使用简单的文件 I/O 来获取对文件的引用(使用new File(filename))。

通常,您希望坚持使用第一个选项。将文件放在任何地方,并将目录添加到类路径中。这样,您的 Java 应用程序不必知道文件的确切位置 - 只要将文件的目录添加到运行时类路径,它就会找到它。

示例(对于第一种方法):

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.
}
于 2012-10-08T04:12:35.723 回答
0

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
于 2012-10-08T04:30:43.553 回答