java web工程普通java类获得当前项目的工程路径?读取xml文件,路径会被定位到tomcat安装路路径的bin下面

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = dbf.newDocumentBuilder();
// System.out.println(System.getProperty("user.dir"));
Document doc =(Document) builder.parse("./Server-Configuration.xml"); // 获取到xml文件
可是在这儿会提示找不到路径,各种方法获取绝对路径都是tomcat下面的bin,我想到获取到工程路径,求高手指教啊!

第1个回答  2012-08-03
String projectPath = this.getClass().getResource("/").getPath().substring(1).replace() + "Server-Configuration.xml";
web应用运行时指向的是你tomcat目录/webapps/应用/web-inf/classes/Server-Configuration.xml
望采纳!
注意,如projectPath中空格的经过base64编码转换后变成了"%20",你还得replace("%20" , " ")。
第2个回答  2012-08-05
D:\Tomact\apache-tomcat-6.0.20\conf\server.xml

该端口号码也是在这里
第3个回答  2012-08-02
class.getResourceAsStream("/xx.xml")这就是项目的绝对路径了 , class是class对象
第4个回答  推荐于2016-02-23
//得到文件
File is=new File("xmlFile/CreateXml.xml");
SAXReader reader=new SAXReader();
//得到Document对象
Document doc=reader.read(is);
//得到Element节点集合
List<Element> list=doc.selectNodes("study/user");
//循环遍历本回答被提问者和网友采纳
相似回答