一般在服务器上部署项目时是一个jar包 旁边放置一个配置文件的文件夹conf,如下图所示 , 在IDEA中结构如上所示
那么怎么做到在IDEA中写的代码能加载配置文件,同时放到服务器上不用修改代码呢?
下面介绍两种方式
package com.lyzx.test;
import java.io.File;
public class T3 {
public static void main(String[] args){
String domain_path = T3.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String file_path = new File("").getAbsolutePath();
System.out.println("通过domain方式获取的jar包的绝对路径(包含jar包的名字)="+domain_path);
System.out.println("通过file相对路径的方式获取的绝对路径(不包含jar包的名字)="+file_path);
//在服务器端时,domain方式获取的路径带有jar包的名字,此时需要做处理
if(domain_path.endsWith(".jar")){
domain_path = domain_path.substring(0,domain_path.lastIndexOf(File.separator));
System.out.println("domain方式服务器端处理后(去掉jar包名)的绝对路径=>"+domain_path);
}
/**
* 下面是三种优雅的加载配置文件的方式
* 个人推荐第一种
*/
File file0 = new File("conf" + File.separator + "log4j.properties");
System.out.println("通过file相对路径的方式加载配置文件::"+file0.getAbsolutePath()+" "+file0.exists());
File file1 = new File(file_path + File.separator + "conf" + File.separator + "log4j.properties");
System.out.println("通过file绝对路径的方式加载配置文件::"+file1.getAbsolutePath()+" "+file1.exists());
//通过这种方式读取的是编译后的位置的配置文件,在IDEA中需要在 target/classes 下放置配置文件的文件夹以及文件
File file2 = new File(domain_path + File.separator + "conf" + File.separator + "log4j.properties");
System.out.println("通过domain的绝对路径加载配置文件::"+file2.getAbsolutePath()+" "+file2.exists());
}
}
本地测试结果如下:
服务器测试结果如下:
ok ,完美解决问题!