温馨提示×

java中properties配置文件怎么使用

小亿
102
2023-09-17 00:54:33
栏目: 编程语言

在Java中,可以使用java.util.Properties类来读取和使用配置文件。

首先,创建一个Properties对象并加载配置文件。可以使用Propertiesload()方法来加载配置文件,传入一个InputStream对象作为参数。例如,假设配置文件名为config.properties,可以使用以下代码加载该配置文件:

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程序中使用配置文件中的属性值了。

0