如何读取path配置文件里面的属性值

本文介绍了一种使用Java的Properties类和FileInputStream从path.properties文件中读取配置信息的方法。详细解释了如何获取特定键(如'className'和'methodName')的值,并提供了完整的代码示例。

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

path.properties文件里面的数据一般都是以’key=value’的形式书写的
              className=com.lovo.bean.Teacher
              methodName=info
    以上,classname相当于key,com.lovo.bean.Teacher相当于key对应的value
    如果要读取path文件里面的值
    必须要使用到java.util下的Properties这个类
    因为需要读取文件,所以还需要用到IO流 InputStream 中的FileInputStream
public class TestProperties {
    // 创建一个静态常量保存配置文件里面的key属性
    private static final String CLASSNAME_KEY = "className";
    private static final String METHODNAME_KEY = "methodName";
    //用于获取配置文件中所有的属性值
    private static String[] sArray = new String[]{CLASSNAME_KEY, METHODNAME_KEY};

    public static void main(String[] args) {
        String className = getClassName();
        //System.out.println(className);

        List<String> sList = getPropertiesValue();
        //System.out.println(sList.toString());
    }

    /**
     * 获取path文件中指定key属性的value
     *
     * @return value
     * <p>
     * 例如以下方法:获取path配置文件中‘className’对应的值
     */
    public static String getClassName() {
        //1. 实例化一个Properties对象pps
        Properties pps = new Properties();
        //2. 实例化一个输入流的对象is
        InputStream is = null;
        //3. 创建一个字符串对象用于保存pps获取的返回值
        String className = null;

        try {
            // 通过path.properties文件路径读取配置文件
            is = new FileInputStream("res/path.properties");
            // 通过pps加载is读取的数据
            pps.load(is);
            // 调用getproperties()方法获取key对应的值,即CLASSNAME_KEY对应的值
            className = pps.getProperty(CLASSNAME_KEY);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 最后返回CLASSNAME_KEY对应的value
        return className;
    }

    /**
     * 获取path文件中所有key属性的value
     *
     * @return value
     * <p>
     * 例如以下方法:获取path配置文件中‘className’,‘methodName’对应的值
     */
    public static List<String> getPropertiesValue() {
        List<String> list = new ArrayList<>();

        Properties pps = new Properties();
        InputStream is = null;

        try {
            is = new FileInputStream("res/path.properties");

            pps.load(is);
            String s = null;
            for (String ss : sArray) {
                s = pps.getProperty(ss);
                list.add(s);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }
}
Python项目中,读取配置文件(如.ini、.conf等)并忽略其中的注释是一项常见的需求。为了实现这一目标,我们可以利用`configparser`模块来解析标准格式的配置文件,并自动跳过注释行。 ### 使用 `configparser` 模块 #### 步骤1:创建示例配置文件 (example.conf) ```ini [DEFAULT] ServerAliveInterval = 45 ; 默认服务器存活间隔时间设置为45秒 Compression=yes # 开启压缩功能 CompressionLevel=9 ; 设置压缩级别为最高 [section_1] host=url_to_your_server.com # 主机地址 port=80 ;; 端口号,默认HTTP端口 ``` > 注意到上述例子中有使用`;` 和 `#` 符号作为注释标识符的情况,在实际应用中只要选择一种即可。 #### 步骤2:编写 Python 脚本进行读取操作 接下来我们将展示如何通过代码读取上面提到的那个配置文件: ```python import configparser def read_config(file_path): config = configparser.ConfigParser(allow_no_value=True) # 允许存在没有赋值的关键字 try: with open(file_path, 'r', encoding='utf-8') as f: config.read_file(f) print("Sections:", config.sections()) for section in ['DEFAULT', 'section_1']: if not config.has_section(section): continue options = config.options(section) print("\nSection: ", section) for option in options: value = config.get(section, option).strip() # 这里可以进一步处理value内容 print(f"{option}: {value}") except Exception as e: print('Error occurred:', str(e)) if __name__ == '__main__': file_path = './example.conf' read_config(file_path) ``` 此段程序将成功加载给定路径下的`.conf`文件,并输出所有非空键对应的值而不会显示注释信息。 ### 关于注释符号的选择 请注意,在 INI 文件规范里面支持的是分号(`;`)用于表示单行注释;然而许多应用程序也接受井号 (`#`) 来做同样的事情。如果你需要兼容这两种风格,则可以在初始化ConfigParser实例之前设定它的特殊参数。 例如: ```python comment_prefixes=(';', '#') config = configparser.ConfigParser(comment_prefixes=comment_prefixes, allow_no_value=True) ``` 这会使得`configparser`能同时识别以`;` 或者 `#`开头的行为注释并且跳过它们。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

国服酱紫牙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值