在DAOFactory类里写个
String path;
Document doc = new SAXReader().read(new file(path+"/daoContext.xml"));
daoContext.xml文件在WEB-INF目录下
path路径怎么写?
尝试:
“/WEB-INF”
“WEB-INF”
“../WEB-INF”
都不对
这种问题最好的解决方法是自己封装一个ResourceLoader,然后将资源文件跟调用者放到同一个目录下,并使用ResourceLoader的load方法加载。具体可以参考这个:
class ResourceLoader{
public static Document getDocument(String file){
Class o = getCallerClass();
InputStream ins = o.getResourceAsStream(file);
Document doc = new SAXReader().read(ins);
return doc;
}
//这里有个小技巧,即通过JAVA虚拟机的栈来获取调用者。
public static Class getCaller(){
StackTraceElement[] stack =
(new Throwable()).getStackTrace();
Class o = null;
try {
o = Class.forName(stack[2].getClassName());
} catch (ClassNotFoundException e) {
System.err.println(e.getMessage());
}
return o;
}
}
然后,你的使用者比如在com.test.path下,叫XMLUser.java
那么将你的xml.xml文件跟XMLUser.java放在同一个目录下,XMLUser.java调用ResourceLoader来加载Document即可。
如:Document doc = ResourceLoader.getDocument("xml.xml");
以new File()的方式,要给出全物理路径才行
path=d:/web/web-inf
new file(path+"/daoContext.xml"));
URL url = DAOFactory.class.getClassLoader().getResource(".");
String path = new File(url.getFile()).getParent() + "/WEB-INF";
Document doc = new SAXReader().read(new File(path+"/daoContext.xml"));
URL url = DAOFactory.class.getClassLoader().getResource(".");
String path = new File(url.getFile()).getParent() + "/WEB-INF";
Document doc = new SAXReader().read(new File(path+"/daoContext.xml"));
需要获取文件在操作系统里面的绝对路径
String path=request.getSession().getServletContext().getRealPath("/WEB-INF");
path=path+"/daoContext.xml";