java中在静态方法中使用配置文件的属性
时间: 2023-08-04 19:29:15 浏览: 61
在Java中,我们可以使用 `java.util.Properties` 类来读取配置文件。我们可以在静态方法中使用这个类来读取配置文件的属性。
假设我们有一个配置文件`config.properties`,它的内容如下:
```
database.url=jdbc:mysql://localhost:3306/test
database.username=root
database.password=123456
```
我们可以在静态方法中使用以下代码读取配置文件中的属性:
```java
public class DatabaseUtil {
private static String url;
private static String username;
private static String password;
static {
Properties props = new Properties();
try {
props.load(DatabaseUtil.class.getResourceAsStream("config.properties"));
url = props.getProperty("database.url");
username = props.getProperty("database.username");
password = props.getProperty("database.password");
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
}
```
在上面的代码中,我们使用了一个静态代码块来读取配置文件,并将配置文件中的属性值存储在静态变量中。然后在`getConnection()`方法中可以使用这些属性值来获取数据库连接。
注意:使用`getResourceAsStream()`方法加载配置文件时,配置文件应该放在类路径下,即和类文件在同一个目录下或在类路径下的某个目录中。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)