转自 http://blog.csdn.net/jian_csdn/article/details/46119313
ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } /** * 获取到webroot里面的数据 */ java.net.URL url2 = classLoader.getResource(""); String ROOT_CLASS_PATH = url2.getPath() + "/"; File rootFile = new File(ROOT_CLASS_PATH); String WEB_INFO_DIRECTORY_PATH = rootFile.getParent() + "/"; File webInfoDir = new File(WEB_INFO_DIRECTORY_PATH); String SERVLET_CONTEXT_PATH = webInfoDir.getParent() + "/"; // 这里 SERVLET_CONTEXT_PATH 就是WebRoot的路径 String path = SERVLET_CONTEXT_PATH + "/" + "file/db.txt";