Java 读取配置文件

762 阅读1分钟

参考

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

代码

需要读取的配置文件

application.properties

db1.username = zhangsan
db1.password = 123

db2.username = lisi
db2.password = 456

文件读取

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

}

image.png

拓展

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

image.png

解决方案一

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

如,测试项目目录结构

image.png

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

image.png

解决方案二

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

注意/指的是src目录下

image.png

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

image.png