Java读取配置文件的方式

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结束的时候就是在server中使用
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根路径找了

 

 

 

上一篇:linux下创建用户及组


下一篇:Varnish 入门