Java读取配置文件的方式-笔记
1 取当前启动目录下的配置文件
一般来讲启动java程序的时候,在启动的目录下会有配置文件
classLoader.getResource("").getFile() 会取到java当前启动项目的目录,然后指定对应的配置文件路径即可比如conf/conf.properties
//取当前启动目录的配置文件
String filePath =classLoader.getResource("").getFile()+”conf/conf.properties”;
2 取classpath下的配置文件
在不考虑多个jar包中有相同路径的同名配置文件的话,可以直接取如下
ClassLoader.getSystemResource("conf/conf.properties")//静态方法
或者
classLoader.getResource("conf/conf.properties") //
小实例
/**
* 取当前启动目录的配置文件,如果没有取加载在当前classpath下的。
* @param classLoader
* @param confClassDirectory
* @return
* @throws FileNotFoundException
*/
public static InputStream getInputStreamByConfPath(ClassLoader classLoader,StringconfClassDirectory) throws FileNotFoundException {
if(confClassDirectory.startsWith("/")) {
confClassDirectory= confClassDirectory.substring(1);
}
//取当前启动目录的配置文件
String filePath = classLoader.getResource("").getFile()+ confClassDirectory;
InputStream in=null;
File file = new File(filePath);
//如果不存在取当前启动的classpath下的
if(!file.exists()) {
in= classLoader.getResourceAsStream(confClassDirectory);
if(null == in) {
in=classLoader.getResourceAsStream("/"+ confClassDirectory);
}
}else{
in=newFileInputStream(file);
}
return in;
}
3 取指定类所在jar包中的配置文件
有的时候A.jar有个文件和B.jar里面也有个文件一样名字一样路径(比如:conf/abc.txt),
如果通过classpath下取conf/abc.txt的只能取到第一个jar包加载的配置文件就是A.Jar,而B.jar的却取不到。
如果这个时候想取B.jar中的配置文件可以先找到jar包的位置然后再找到对应的配置文件路径即文件。
可以如下实现这种功能
/**
*根据class类找到对应的jar取指定的配置文件
* @param cls
* @param confClassDirectory
* @return
* @throws IOException
*/
public static InputStream getInputStreamByJarFileConfPath(Class<?> cls,StringconfClassDirectory) throws IOException {
String jarPath=cls.getProtectionDomain().getCodeSource().getLocation().getFile();
if(confClassDirectory.startsWith("/")) {
confClassDirectory= confClassDirectory.substring(1);
}
if(jarPath==null) {
returnnull;
}
InputStream in=null;
//判断如果是以jar结束的时候就是在服务器中使用
if(jarPath.endsWith(".jar")) {
JarFile jarFile = new JarFile(jarPath);
JarEntry entry =jarFile.getJarEntry(confClassDirectory);
in= jarFile.getInputStream(entry);
}else{
//就是可能本地直接依赖项目的使用
File file=new File(jarPath+confClassDirectory);
if(file.exists()) {
in=newFileInputStream(file);
}
}
return in;
}
}
当然好像可以通过
Enumeration<URL> urlss=ClassLoader.getSystemResources("conf/conf.properties");
while(urlss.hasMoreElements()){
System.out.println(urlss.nextElement().getFile());
}
取到所有的conf/conf.properties的配置文件。
也可以通过判断路径来判断。
4 取class下的配置文件
用Class.getResource不加/(下划线)就是从当前包开始找,一般不推荐,毕竟配置文件配置不方便不说且,maven好像默认打包在src/main/java下的配置文件时不打进去的。
加上/(下划线)就是从classpath根路径找了