方法一:相对路径设置配置文件
(1)在jar包同级目录创建配置文件conf.properties并写入配置数据:
confdata=data
(2)开始写入自动化测试代码
//from www.fhadmin.cnpublic class test{ public string getdata() throws ioexception { //读取配置文件 properties properties = new properties(); file file = new file("conf.properties"); fileinputstream fis = new fileinputstream(file); properties.load(fis); fis.close(); //获取配置文件数据 string confdata = properties.getproperty("confdata"); system.out.println(confdata); }}
(3)执行jar包
java -jar jarnanexxx
方法二:绝对路径设置配置文件
解决问题:使用相对路径的方法在jar包同级目录手动执行jar包时没有问题,但使用linux系统的crontab文件定时调度时报错,原因:因为我们手动执行某个脚本时,是在当前shell环境下进行的,程序能找到环境变量;而系统自动执行任务调度时,除了默认的环境,是不会加载任何其他环境变量的。因此就需要在crontab文件中指定任务运行所需的所有环境变量,或者在程序中使用绝对路径。
(1)在jar包同级目录创建配置文件conf.properties并写入配置数据:
confdata=data
(2)开始写入自动化测试代码
//from www.fhadmin.cnpublic class test{ public string getdata() throws ioexception { //获取jar包同级目录 string path = this.getclass().getprotectiondomain().getcodesource().getlocation().getpath(); string[] pathsplit = path.split("/"); string jarname = pathsplit[pathsplit.length - 1]; string jarpath = path.replace(jarname, ""); string pathname=jarpath+"minhang.properties"; system.out.println("配置文件路径:"+jarpath); //读取配置文件 properties properties = new properties(); file file = new file(pathname); fileinputstream fis = new fileinputstream(file); properties.load(fis); fis.close(); //获取配置文件数据 string confdata = properties.getproperty("confdata"); system.out.println(confdata); }}
(3)执行jar包
java -jar jarnanexxx
以上就是springboot怎么运行jar包读取外部配置文件的详细内容。