以下是一个示例,展示如何使用 Java 读取配置文件并访问配置项。这里,我们将使用 java.util.Properties
类读取配置文件。
1. 创建配置文件
在项目的 src/main/resources
目录下创建一个名为 config.properties
的配置文件,内容如下:
db.url=jdbc:mysql://localhost:3306/mydb
db.username=root
db.password=secret
app.debug=true
2. 编写代码读取配置文件
以下是 Java 代码示例,展示如何读取配置文件并访问其中的配置项:
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigReader {
private Properties properties;
public ConfigReader(String configFileName) {
properties = new Properties();
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(configFileName)) {
if (inputStream != null) {
properties.load(inputStream);
} else {
throw new IOException("Configuration file '" + configFileName + "' not found in the classpath");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public String getProperty(String key) {
return properties.getProperty(key);
}
public static void main(String[] args) {
// 获取当前类的路径,config.properties文件路径
String classPath = ConfigReader.class.getProtectionDomain().getCodeSource().getLocation().getPath();
System.out.println("Class path: " + classPath);
ConfigReader configReader = new ConfigReader("config.properties");
String dbUrl = configReader.getProperty("db.url");
String dbUsername = configReader.getProperty("db.username");
String dbPassword = configReader.getProperty("db.password");
String appDebug = configReader.getProperty("app.debug");
System.out.println("Database URL: " + dbUrl);
System.out.println("Database Username: " + dbUsername);
System.out.println("Database Password: " + dbPassword);
System.out.println("App Debug: " + appDebug);
}
}