获取web环境中的相应路径的工具类
/** * 获取web环境中的相应路径 * * @author xwz * @date Jan 5, 2010 */ public class PathUtil { public static final String CLASSES = getClassesPath(); public static final String WEB_INF = getWEB_INFPath(); public static final String WEB_ROOT = getWEB_ROOTPath(); /** 获取某个类所在的路径 */ public static String getClassPath(Class cls) { String s = cls.getResource("").getPath(); if (s.startsWith("/")) s = s.substring(1); return s; } /** 获取classes目录下的资源流 */ public static InputStream getInputStreamFromClasses(String packageNameAndFileName) { try { FileInputStream fin = new FileInputStream(CLASSES + packageNameAndFileName); return fin; } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } /** 获取WEB-INF目录下的资源流 */ public static InputStream getInputStreamFromWebInf(String fileName) { try { FileInputStream fin = new FileInputStream(WEB_INF + fileName); return fin; } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } /** * 从jar文件获取资源流 * * @param oneClassInJar jar里面的一个类 * @param fileName * @return * @author xwz */ public static InputStream getInputStreamFromJar(Class oneClassInJar, String fileName) { InputStream is = oneClassInJar.getResourceAsStream(fileName); return is; } private static String getClassesPath() { String s = PathUtil.class.getResource("/").getPath(); if (s.startsWith("/")) s = s.substring(1); return s; } private static String getWEB_INFPath() { String s = ""; String classes = getClassesPath(); int last = classes.lastIndexOf("classes/"); return classes.substring(0, last); } private static String getWEB_ROOTPath() { String s = ""; String classes = getClassesPath(); int last = classes.lastIndexOf("WEB-INF/classes/"); return classes.substring(0, last); } public static void main(String[] args) { System.out.println(PathUtil.CLASSES); System.out.println(PathUtil.WEB_INF); System.out.println(PathUtil.WEB_ROOT); System.out.println(PathUtil.getClassPath(User.class)); InputStream classesIn = PathUtil.getInputStreamFromClasses("config/fckeditor.cfg"); InputStream webinfIn = PathUtil.getInputStreamFromWebInf("tlds/c.tld"); InputStream jarIn = PathUtil.getInputStreamFromJar(User.class, "/resource/res.txt"); } }
?