如何在java中使用记事本在项目外部调用database.properties?
我想在项目之外创建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
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()
获取文件的输入流database.properties
文件的确切位置,您可以使用简单的文件I/O来获取对该文件的引用(使用新文件(文件名)
)将属性文件存储在首选位置。然后执行以下操作:
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