Java Properties 类使用示例:配置文件读取与属性访问
下面是一个使用 Java Properties 类的简单示例,演示如何从配置文件中读取数据:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesExample {
public static void main(String[] args) {
// 创建一个新的 Properties 对象
Properties props = new Properties();
try {
// 加载配置文件
props.load(new FileInputStream('config.properties'));
// 获取属性值
String dbUrl = props.getProperty('dbUrl');
String username = props.getProperty('username');
String password = props.getProperty('password');
// 输出属性值
System.out.println('dbUrl: ' + dbUrl);
System.out.println('username: ' + username);
System.out.println('password: ' + password);
} catch (IOException e) {
e.printStackTrace();
}
}
}
在这个示例中,我们首先创建了一个新的 Properties 对象。然后,我们使用 props.load() 方法加载了一个名为 'config.properties' 的配置文件。接下来,我们使用 props.getProperty() 方法获取配置文件中的属性值。最后,我们输出这些属性值。
原文地址: https://www.cveoy.top/t/topic/nAnp 著作权归作者所有。请勿转载和采集!