#

Find your resources

Kommt häufiger vor: man hat eine Properties oder Konfigurationsdatei unter WEB-INF oder bei den Klassen und weiß nicht, wie man sie laden soll.

public static final File getFileResource(String resourcename){
   	URL in = ClassLoader.getSystemClassLoader().getResource(resourcename);
	if (in==null){
		in = Thread.currentThread().getContextClassLoader()
			.getResource(resourcename);
	}
	if (in==null) return null;
	return new File(in.getFile());
}
Tags:

One Response to “Find your resources” »»

  1. Comment by Secco | 10:58 25.09.08|X

    In einigen Fällen reicht das nicht, z. B. wenn man eine Webapplikation hat, die Datei aber aus einer Testklasse und nicht aus der Webapplikation laden möchte. Folgende Erweiterung hilft hier:

    public static final File getFileResource(String resourcename){
       	URL in = ClassLoader.getSystemClassLoader().getResource(resourcename);
    	if (in==null){
    		in = Thread.currentThread().getContextClassLoader()
    			.getResource(resourcename);
    	}
    	if (in==null){
    		final String classPath = System.getProperty("java.class.path",".");
    		final String [] paths = classPath.split("\\Q"+File.pathSeparator+"\\E");
    		final HashSet<File> checkedPaths = new HashSet<File>(paths.length);
    		File f, ft;
    		int index;
    		for (int i=0; i<paths.length; i++){
    			f = new File(paths[i]);
    			if (f.isFile()){
    				f = new File(f.getParent());
    			}
    			if (!checkedPaths.contains(f)){
    				ft = new File(f.getPath(), resourcename);
    				if (ft.exists()){
    					return ft;
    				}
    				index = f.getPath().indexOf(File.separator+"WEB-INF"+File.separator);
    				if (index>-1){
    					ft = new File(f.getPath().substring(0, index+8), resourcename);
    					if (!checkedPaths.contains(ft)){
    						if (ft.exists()){
    							return ft;
    						}
    						checkedPaths.add(ft);
    					}
    				}
    				index = f.getPath().indexOf(File.separator+"web-inf"+File.separator);
    				if (index>-1){
    					ft = new File(f.getPath().substring(0, index+8), resourcename);
    					if (!checkedPaths.contains(ft)){
    						if (ft.exists()){
    							return ft;
    						}
    						checkedPaths.add(ft);
    					}
    				}
    				checkedPaths.add(f);
    			}
    		}
    		return null;
    	}
    	return new File(in.getFile());
    }

Leave a Reply »»

Note: All comments are manually approved to avoid spam. So if your comment doesn't appear immediately, that's ok. Have patience, it can take some days until I have the time to approve my comments.