java读取配置文件示例代码

以下是一个示例,展示如何使用 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);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值