java如何读取properties文件将参数值配置到静态变量
作者:祁仙森
这篇文章主要介绍了java如何读取properties文件将参数值配置到静态变量问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
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());
}
成功,没有出现乱码现象
java相对路径与properties文件读取
// 打包jar同目录下的application.properties,未打包 bin/application.properties
File file = new File(path + "application.properties");
Properties properties = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(file));
properties.load(in);
int port = Integer.parseInt(properties.getProperty("server.port"));
// 遍历properties
// Iterator<String> it = properties.stringPropertyNames().iterator();
// while(it.hasNext()) {
// String key = it.next();
// System.out.println(key+":" + properties.getProperty(key));
//
// }总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
