天天看點

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(jarPath==null) {

returnnull;

//推斷假設是以jar結束的時候就是在server中使用

if(jarPath.endsWith(".jar")) {

JarFile jarFile = new JarFile(jarPath);

JarEntry entry =jarFile.getJarEntry(confClassDirectory);

in= jarFile.getInputStream(entry);

//就是可能本地直接依賴項目的使用

File file=new File(jarPath+confClassDirectory);

if(file.exists()) {

in=newFileInputStream(file);

}

當然好像能夠通過

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根路徑找了