[Java] 使用配置文件保存参数

公司有一个常驻的项目,日常需要改改参数什么的,如果每次都逐个访问代码文件就太麻烦了,所以决定写到properties文件里,简化操作流程。

读取资料

通常情况下,我们可以使用如下方法读取properties文件的信息:

public void test_method_one() {
    FileInputStream file = null;
    String fileUrl = "C:/config.properties";
    try {
        System.out.println("Hello World");
        Properties properties = new Properties();
        file = new FileInputStream(fileUrl);
        properties.load(file);
        System.out.println(properties.getProperty("activityName"));
        System.out.println(properties.getProperty("redBegBlessing"));
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {
            if (file != null) {
                file.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

利用该方法确实可以读取到指定路径的文件,但问题在于读取出来的中文会是乱码,这是因为我们在读取的时候没有设定字符集,故显示出来的内容全是乱码。参考了网络上的资料后,我们可以改成下列这种方式:

@Test
public void ReadProperties() {
    System.out.println("Hello World");
    FileInputStream file = null;
    BufferedInputStream in = null;
    try {
        Properties properties = new Properties();
        file = new FileInputStream(fileUrl);
        in = new BufferedInputStream(file);
        properties.load(new InputStreamReader(in, StandardCharsets.UTF_8));
        for (String key : properties.stringPropertyNames()) {
            String info = properties.getProperty(key);
            System.out.println(key + ": " + info);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (in != null) {
                in.close();
            }
            if (file != null) {
                file.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

参考资料

本次学习参考了以下网络资源,感谢各位dalao们的贡献
[1] java读取.properties配置文件的几种方法
[2] Java中文件的相对路径与绝对路径
[3] Java读写.properties文件实例,解决中文乱码问题

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值