Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中使用记事本在项目外部调用database.properties?_Java_Database_Properties - Fatal编程技术网

如何在java中使用记事本在项目外部调用database.properties?

如何在java中使用记事本在项目外部调用database.properties?,java,database,properties,Java,Database,Properties,我想在项目之外创建database.properties,因此,当我将它们构建到jar中时,如果我想更改其中的内容(数据库配置),我可以轻松地完成,而无需再次打开我的项目。那么该怎么办呢?首先,将database.properties文件放在您想要的位置 然后,执行以下操作之一: try { String myPropertiesFilePath = "D:\\configuration.properties"; // path to your properties file

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

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

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

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) {

}
  • database.properties
    所在的目录添加到类路径。然后使用
    Thread.currentThread().getContextClassLoader().getResource()
    获取文件的URL,或者使用
    getResourceAsStream()
    获取文件的输入流
  • 如果您不介意Java应用程序知道
    database.properties
    文件的确切位置,您可以使用简单的文件I/O来获取对该文件的引用(使用
    新文件(文件名)
  • 通常,你会坚持第一种选择。将文件放在任意位置,并将目录添加到类路径。这样,Java应用程序就不必知道文件的确切位置——只要将文件的目录添加到运行时类路径中,它就会找到文件

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


    将属性文件存储在首选位置。然后执行以下操作:

    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) {
    
    }
    
    现在,您可以轻松地从文件中获取字符串形式的属性:

    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
    
    您的
    配置.properties
    文件可能如下所示:

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