自定義框架-加載配置文件

在web.xml配置自定義的servlet來訪問加載所需資源

//加載配置文件

private void loadConfig(ServletConfig config) {

boolean b = false;

String configFile = config.getInitParameter("config").trim();

//判斷參數是否包含classpath

if(configFile.contains("classpath")){

configFile = configFile.substring(configFile.indexOf("classpath")+10);

b = true;

}

//檢測是否包含分隔符

String[] files = configFile.split(",");

for (int i = 0 , j = files.length; i < j; i++) {

String filestr = files[i];

//獲取參數指定文件路徑

int index = filestr.lastIndexOf("/");

String cpath = filestr.substring(0, index);

String fileName = filestr.substring(index+1);

String wpath = null;

if(b){

//通過類加載器加載資源路徑

wpath = this.getClass().getClassLoader().getResource(cpath).getPath();

}else{

//

wpath = this.getServletContext().getRealPath(cpath);

}

//判斷路徑存不存在 

File dir = new File(wpath);

if(!dir.exists()){

System.err.println((new StringBuilder("Warning directory:"))

.append(wpath).append("不存在!").toString());

}else{

File[] listfile = dir.listFiles();

listResource = new ArrayList<File>();

//檢測是否包含通配符

if(fileName.contains("*")){

//獲取文件通配符正則表達式

String regexp = fileName.replace("*", "[\\s\\S]*"); 

for (int t = 0; t < listfile.length; t++) {

File file = listfile[t];

if(file.isDirectory()){//若是目錄則繼續匹配下一個文件

continue;

}

if(file.getName().matches(regexp)){

listResource.add(file);

System.out.println("Load directext config:" + file.getAbsolutePath());

}

}

}else{

File file = new File(new StringBuilder(wpath).append("/").append(fileName).toString());

if(!file.exists()){

System.err.println((new StringBuilder("Warning file:"))

.append(file.getAbsolutePath()).append("不存在!").toString());

}

listResource.add(file);

System.out.println("Load directext config:" + new StringBuilder(file.getAbsolutePath()));

}

}

}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章