Web项目中java类读取WebRoot目录下的配置文件

需求:在Web项目中,java类读取WebRoot目录下的配置文件,例如在Dao层读取,没有request,该如何读取?假设在WebRoot下有一个文件夹:config,里面有配置文件

conf.properties内容为:

ip=127.0.0.1
port=8080

.

code:

 //获取项目部署的目录到WEB—INF的上一级
	   private String getClassPath(){ 
	        String strClassName = getClass().getName(); 
	        String strPackageName = ""; 
	        if(getClass().getPackage() != null) { 
	            strPackageName = getClass().getPackage().getName(); 
	        } 
	        String strClassFileName = ""; 
	        if(!"".equals(strPackageName)){
	            strClassFileName = strClassName.substring(strPackageName.length() + 1,strClassName.length()); 
	        } 
	        else { 
	            strClassFileName = strClassName; 
	        } 
	        URL url = null; 
	        url = getClass().getResource(strClassFileName + ".class"); 
	        String strURL = url.toString();
	        strURL = strURL.substring(strURL.indexOf( "/" ) + 1,strURL.lastIndexOf( "WEB-INF" ));
	        return strURL; 
	    }

2.根据上述方法读取配置文件,并读取ip和port的内容

code:

//获取配置文件信息
	public    void GetDate(){
		String path=getClassPath()+"config/conf.properties";
		String ip="";
		String port="";
		Properties prop = new Properties();     
	        try{
	            //读取属性文件
	           InputStream in = new BufferedInputStream (new FileInputStream(path));
	           prop.load(in);     ///加载属性列表
	           ip=prop.getProperty("ip");
	           port=prop.getProperty("port");
	           in.close();
	        }catch(Exception e){
                    System.out.println(e);
               }
		
			System.out.println("IP:"+ip+"PORT:"+port);	
		}


猜你喜欢

转载自blog.csdn.net/xadjccl/article/details/79492814