在 Java servlet外部 获取WEB-INF 路径

今天碰到一个问题,就是在Java servlet外部获取WEB-INF的路径,在网上搜了一圈都没有找到,最后接近放弃的时候在一个被墙了的网站上面找到的方法。

记录如下:

import java.io.File;

/**
 * This class search for the web inf class path and gives many path from that
 * Licence LGPLv3
 * Publish 2012-10-03
 * @author Deisss
 * @version 0.1
 */
public class ClassPath{
	private static ClassPath instance = null;
	private String webInfPath, webXmlPath, configXmlPath;

	/**
	 * The constructor will get the webInfPath and store it until the app close
	 */
	private ClassPath(){
		File myClass = new File(getClass().getProtectionDomain().getCodeSource().getLocation().getFile());

		//The package name give the number of parentFile to apply
		//We add 3 : the first one is the .class name, the "." counted are one less, and the package is
		//inside a classes folder. So 3.
		int packageSubFolder = getClass().getPackage().getName().replaceAll("[^.]", "").length() + 3;

		//Place the file to the good parent file to point into the web inf
		for(int i=0; i<packageSubFolder; i++){
			myClass = myClass.getParentFile();
		}

		this.webInfPath = myClass.getAbsolutePath().replaceAll("%20", " ") + File.separator;
		this.webXmlPath = this.getWebInfPath() + "web.xml";
		this.configXmlPath = this.getWebInfPath() + "config.xml";
	}

	/**
	 * Singleton structure
	 * @return himself
	 */
	public static ClassPath getInstance(){
		if(instance == null){
			instance = new ClassPath();
		}
		return instance;
	}


	/**
	 * Get back the WEB-INF path
	 * @return The WEB-INF path
	 */
	public String getWebInfPath(){
		return this.webInfPath;
	}

	/**
	 * Get back the WEB-INF/web.xml path
	 * @return The WEB-INF/web.xml path
	 */
	public String getWebXmlPath(){
		return this.webXmlPath;
	}

	/**
	 * Get back the WEB-INF/config.xml path
	 * @return The WEB-INF/config.xml path
	 */
	public String getConfigXmlPath(){
		return this.configXmlPath;
	}
}

把这个类放在一个web project的任意位置就可以了。


下面是一个例子:

File file = new File(ClassPath.getInstance().getConfigXmlPath());
DataInputStream dis = null;

try{
	dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
	while(dis.available() != 0){
		System.out.println(dis.readLine());
	}
	dis.close();
}catch(FileNotFoundException e){
	e.printStackTrace();
}catch(IOException e){
	e.printStackTrace();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值