properties文件操作

本文介绍了一种使用Java的Properties类来读取配置文件的方法。通过一个具体的例子展示了如何加载和读取.properties文件中的属性,并提供了关闭资源的实用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

properties文件操作类

可以使用java.util.Properties读取.properties文件中的内容


import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.core.io.ClassPathResource;

/**properties配置文件读取*/

public class ConfigReader
{
    // 文件路径
    private static final String file = "sql.properties";
    
    //配置保存类
    private static final Properties props = new Properties();
    
    static
    {
        ClassPathResource resource = new ClassPathResource(file);
        InputStream inputStream = null;
        try
        {
            inputStream = resource.getInputStream();
            props.load(inputStream);
        }
        catch (Exception e)
        {
           //打印错误日志
        }
        finally
        {
            closeQuietly(inputStream);
        }
    }
    
    /**
     * 根据名字获取
     */
    public static String getProperty(String propertyName)
    {
        return props.getProperty(propertyName);
    }
    /*
    *资源关闭
    */
    public static void closeQuietly(Closeable closeable)
    {
        if (null != closeable)
        {
            try
            {
                closeable.close();
            }
            catch (Exception e)
            {
                
            }
        }
    }
}

config.properties文件内容

name=zqq
age=18

使用

ConfigReader.getProperty("name");

转载于:https://www.cnblogs.com/z00377750/p/9376171.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值