`
qtlkw
  • 浏览: 300236 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

从类路径中读取文件

    博客分类:
  • JAVA
 
阅读更多
从类路径中读取文件
Case 1, 用getResource:   
    public static final String CUSTOM_FUNCTION_FILE_NAME = "SRT_MENU2FUNCTION.xml";
    public static final String CONFIGURATION_PATH = "WEB-INF/cfg";

    /**
     * Look up and load the custom function definition file
     * First, it will load the path of custom function base on the value from the ServletContext, 
     * and if the path still is null, it will load it base on the class path of this class
     * @return
     * @throws GenException
     */
    private File getCustomFunctionFile() throws GenException
    {
	String filePath = servletContainerPath;
	try{
        	if(filePath == null || filePath.trim().length() < 1){
        	    
        	    URI uri = new URI(this.getClass().getResource("/").toString());
        	    String classPath = uri.getPath();
        	    filePath = classPath + ".." + File.separator + ".." + File.separator;
        	}
        	
        	File file = new File(new File(filePath, CONFIGURATION_PATH), CUSTOM_FUNCTION_FILE_NAME);
        	if (file.exists() && file.canRead())
        	{
        	    return file;
        	}
	}catch(URISyntaxException e){
	    throw new GenException("Retrieve the " + CUSTOM_FUNCTION_FILE_NAME + " path error!\n" + e);
	}
	
	throw new GenException("Can't find the custom function file - " + CUSTOM_FUNCTION_FILE_NAME);
    }


Note: 用getResource("/").getPath(),读取application工程路径会有问题,当工程路径包含空格,返回值会包含%20,详情参照: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4466485,解决方法如上引入URI再取其值。

Case 2, 用getResourceAsStream:
/**
     * Load the custom function file and prepare for parsing
     * 
     * @return
     * @throws GenException
     */
    public Document getDocument() throws GenException
    {
	try
	{
	    DOMParser parser = new DOMParser();
	    parser.parse(new InputSource(this.getClass().getResourceAsStream(CUSTOM_FUNCTION_FILE_NAME)));
	    return parser.getDocument();
	}
	catch (IOException ioe)
	{
	    logger.error(ioe.getMessage());
	    throw new GenException("Error occurs while reading - " + CUSTOM_FUNCTION_FILE_NAME + "\n");
	}
	catch (SAXException sax)
	{
	    logger.error(sax.getMessage());
	    throw new GenException("Error occurs while parsing - " + CUSTOM_FUNCTION_FILE_NAME + "\n");
	}
    }

首先,Java中的getResourceAsStream有以下几种:
1. Class.getResourceAsStream(String path) : path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取。其只是通过path构造一个绝对路径,最终还是由ClassLoader获取资源。

2. Class.getClassLoader.getResourceAsStream(String path) :默认则是从ClassPath根下获取,path不能以’/'开头,最终是由ClassLoader获取资源。

3. ServletContext. getResourceAsStream(String path):默认从WebAPP根目录下取资源,Tomcat下path是否以’/'开头无所谓,当然这和具体的容器实现有关。

4. Jsp下的application内置对象就是上面的ServletContext的一种实现。

其次,getResourceAsStream 用法大致有以下几种:

第一: 要加载的文件和.class文件在同一目录下,例如:com.x.y 下有类me.class ,同时有资源文件myfile.xml
那么,应该有如下代码:
me.class.getResourceAsStream("myfile.xml");

第二:在me.class目录的子目录下,例如:com.x.y 下有类me.class ,同时在 com.x.y.file 目录下有资源文件myfile.xml
那么,应该有如下代码:
me.class.getResourceAsStream("file/myfile.xml");

第三:不在me.class目录下,也不在子目录下,例如:com.x.y 下有类me.class ,同时在 com.x.file 目录下有资源文件myfile.xml
那么,应该有如下代码:
me.class.getResourceAsStream("/com/x/file/myfile.xml");

总结一下,可能只是两种写法
第一:前面有 "/"
"/"代表了工程的根目录,例如工程名叫做myproject,"/"代表了myproject
me.class.getResourceAsStream("/com/x/file/myfile.xml");

第二:前面没有 "/"
代表当前类的目录
me.class.getResourceAsStream("myfile.xml");
me.class.getResourceAsStream("file/myfile.xml");

最后,自己的理解:
getResourceAsStream读取的文件路径只局限与工程的源文件夹中,包括在工程src根目录下,以及类包里面任何位置,但是如果配置文件路径是在除了源文件夹之外的其他文件夹中时,该方法是用不了的。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics