当前位置: 移动技术网 > IT编程>开发语言>Java > java读取properties文件将参数值配置到静态变量

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

2020年07月17日  | 移动技术网IT编程  | 我要评论

将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());
}

成功,没有出现乱码现象 

本文地址:https://blog.csdn.net/xibei19921101/article/details/107342434

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网