Java 读取配置文件

参考

Java中读取properties配置文件的八种方式总结_java读取配置文件的方式-CSDN博客

代码

需要读取的配置文件

application.properties

ini 复制代码
db1.username = zhangsan
db1.password = 123

db2.username = lisi
db2.password = 456

文件读取

java 复制代码
package demo1;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

public class Encrypt {

	public static void main(String[] args) throws Exception {
		InputStream inputStream = new FileInputStream("application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        String property = properties.getProperty("db1.username");
        System.out.println("property = " + property);
	}

}

拓展

打包之后运行jar包,会爆配置文件找不到的错误

解决方案一

需要根据项目的配置文件的地址,新建相关文件

如,测试项目目录结构

添加对应目录结构的配置文件后,可以正常运行

解决方案二

修改文件的读取流:InputStream inputStream = Encrypt.class.getResourceAsStream("/application.properties") ;

注意/指的是src目录下

打包后无需新建配置文件也可读取

相关推荐
jeffer_liu3 小时前
Spring AI 生产级实战:裁判员
java·人工智能·后端·spring·大模型
金銀銅鐵4 小时前
用 Tkinter 实现简单的猜数字游戏
后端·python
copyer_xyf4 小时前
Python 模块与包的导入导出
前端·后端·python
夜微凉44 小时前
三、Spring
java·后端·spring
copyer_xyf4 小时前
Python venv 虚拟环境
前端·后端·python
copyer_xyf6 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python
Full Stack Developme6 小时前
Spring AOP 与 AspectJ
java·后端·spring
IT_陈寒7 小时前
被Vite的动态导入坑了一整天,原来问题出在这
前端·人工智能·后端
码事漫谈7 小时前
你的 AI 编程助手,为什么总在“乱来”?
后端
星浩AI8 小时前
接手 20 万行代码从哪读起?Understand-Anything 把仓库变成可探索的知识图谱
后端·github·claude