java读取properties文件将参数值配置到静态变量

将test.properties的文件读取赋值给静态变量

创建一个final类

可以两种方式读取test.properties配置文件

第一种:此方法可以写配置文件的绝对路径

InputStream is = new BufferedInputStream(new FileInputStream(new File("F:\\java\\idea-workspace\\javaDemoForTest\\src\\test.properties")));

 第二种:此时test.properties配置文件的路径与包同级,在src目录下

InputStream is = ReadProperties.class.getClassLoader().getResourceAsStream("test.properties");
package com.gangye;

import java.io.*;
import java.util.Properties;

/**
 * @Classname ReadProperties
 * @Description 读取文件到静态变量
 * @Date 2020/7/9 17:03
 * @Created by gangye
 */
public final class ReadProperties {
    private static Integer id;
    private static String name;
    private static String address;

    static {
        Properties prop = new Properties();
        try {
            // 方法一:通过输入缓冲流进行读取配置文件,文件可以传入绝对路径
            //InputStream is = new BufferedInputStream(new FileInputStream(new File("F:\\java\\idea-workspace\\javaDemoForTest\\src\\test.properties")));
            InputStream is = ReadProperties.class.getClassLoader().getResourceAsStream("test.properties");
            // 传入编码格式解决中文乱码
            prop.load(new InputStreamReader(is,"utf-8"));
            id = Integer.valueOf(prop.getProperty("id"));
            name = prop.getProperty("name");
            address = prop.getProperty("address");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private ReadProperties(){}

    public static Integer getId(){
        return id;
    }

    public static String getName(){
        return name;
    }

    public static String getAddress(){
        return address;
    }

}

注意,上述在加载文件的时候

prop.load(new InputStreamReader(is,"utf-8"));

使用配置文件对应的编码格式,不然会出现乱码现象

编写测试类,打印静态变量的值

public static void main(String[] args) {
    System.out.println(ReadProperties.getId());
    System.out.println(ReadProperties.getName());
    System.out.println(ReadProperties.getAddress());
}

成功,没有出现乱码现象 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值