java如何读取properties文件将参数值配置到静态变量
更新时间:2023年08月14日 14:31:15 作者:祁仙森
这篇文章主要介绍了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));
//
// }总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Mybatis-plus 批量插入太慢的问题解决(提升插入性能)
公司使用的Mybatis-Plus操作SQL,用过Mybatis-Plus的小伙伴一定知道他有很多API提供给我们使用,但是批量插入大数据太慢应该怎么解决,本文就详细的介绍一下,感兴趣的可以了解一下2021-11-11
Java lambda list转换map时,把多个参数拼接作为key操作
这篇文章主要介绍了Java lambda list转换map时,把多个参数拼接作为key操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2020-08-08
Spring中的@ExceptionHandler异常拦截器
这篇文章主要介绍了Spring中的@ExceptionHandler异常拦截器,Spring的@ExceptionHandler可以用来统一处理方法抛出的异常,给方法加上@ExceptionHandler注解,这个方法就会处理类中其他方法抛出的异常,需要的朋友可以参考下2024-01-01


最新评论