java中properties配置文件如何使用
在Java中,可使用`java.util.Properties`类来读取和使用配置文件。
首先,创建一个`Properties`对象并加载配置文件。可使用`Properties`的`load()`方法来加载配置文件,传入一个`InputStream`对象作为参数。例如,假定配置文件名为`config.properties`,可使用以下代码加载该配置文件:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
// 使用配置文件中的属性值
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
}
```
然后,可使用`Properties`对象的`getProperty()`方法根据配置文件中的键获得对应的值。
配置文件`config.properties`的内容以下:
```
username=admin
password=123456
```
运行上述代码,将输出:
```
Username: admin
Password: 123456
```
这样你就能够在Java程序中使用配置文件中的属性值了。
TOP