[英]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. 我想在项目外部放置database.properties,所以当我将其内容构建到jar
时要更改其内容(数据库配置)时,无需再次打开项目就可以轻松地做到这一点。 So what to do? 那么该怎么办?
First, place the database.properties
file in the location you'd like it to be in. 首先,将database.properties
文件放置在您想要的位置。
Then, do one of the following: 然后,执行下列操作之一:
database.properties
is located, to the classpath. 将database.properties
所在的目录添加到类路径。 Then use Thread.currentThread().getContextClassLoader().getResource()
to get a URL to the file, or getResourceAsStream()
to get an input stream for the file. 然后使用Thread.currentThread().getContextClassLoader().getResource()
获取文件的URL,或使用getResourceAsStream()
获取文件的输入流。 database.properties
file, you can use simple File I/O to obtain a reference to the file (use new File(filename)
). 如果您不介意Java应用程序知道database.properties
文件的确切位置,则可以使用简单的File I / O获得对该文件的引用(使用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. 这样,您的Java应用程序不必知道文件的确切位置-只要将文件目录添加到运行时类路径中,它就会找到它。
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: 您的configuration.properties
文件可能如下所示:
demo.datasource.context=jdbc/demo-DS
demo.datasource.password=123
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.