日期:2014-05-16  浏览次数:20731 次

这个文件路径该怎么写;
问题描述:开发一个用户登录注册的web程序,采用三层架构模式开发;数据库是一个users.xml文件;
存放在src目录下;在设计dao层的实现模块时Sax解析获取users.xml文件碰到问题;估计是路径获取,但不知道怎么改; 
public class UserDaoImpl {
// 根据传递过来的user对象将其添加到xml文档中,即数据库;这涉及到文档的获取,以及写入,有公共代码;
// 同时考虑到分模块写,可以做出操作文档的工具类;
@SuppressWarnings("deprecation")
public void add(User user) {
try {
System.out.print("dao");
Document document = XMLUtils.getDocument();
Element root = document.getRootElement();
Element user_tag = root.addElement("user");
user_tag.setAttributeValue("id", user.getId());
user_tag.setAttributeValue("username", user.getUsername());
user_tag.setAttributeValue("password", user.getPassword());
user_tag.setAttributeValue("email", user.getEmail());
user_tag.setAttributeValue("birthday", user.getBirthday()
.toLocaleString());
user_tag.setAttributeValue("nickname", user.getNickname());
XMLUtils.write2Xml(document);
} catch (Exception e) {
throw new RuntimeException(e);// 异常转型后抛出;
}

}

public User find(String username, String password) {
User user = new User();
try {
Document document = XMLUtils.getDocument();
// 用xpath技术进行解析;
Element e = (Element) document.selectSingleNode("user[@usename='"
+ username + "' and @password='" + password + "']");
// 对e进行判断,如果为空,则说明没有找到,返回空,退出;
if (null == e) {
return null;
} else {
user.setId(e.attributeValue("id"));
user.setUsername(e.attributeValue("username"));
user.setPassword(e.attributeValue("password"));
user.setEmail(e.attributeValue("email"));
DateFormat df = DateFormat.getDateInstance();
Date date = df.parse(e.attributeValue("birthday"));
user.setBirthday(date);
user.setNickname(e.attributeValue("nickname"));
return user;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}

public boolean find(String username) {
try {
return (XMLUtils.getDocument().selectSingleNode("user[@username='"
+ username + "']")) == null ? false : true;
} catch (DocumentException e) {
throw new RuntimeException(e);
}
}
}这个是dao层的实现模块;
其中用到的工具类XMLUtils为
public class XMLUtils {
//根据路径读取xml文件,
public static String filepath;
static{
filepath=XMLUtils.class.getClassLoader().getResource("users.xml").getPath();//******出问题的地方;
}
public static Document getDocument() throws DocumentException{
System.out.print("xmlget");
SAXReader reader=new SAXReader();
Document document=reader.read(new File(filepath));
return document;
}
public static void write2Xml(Document document) throws IOException{
System.out.print("xmlwrite");
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer=new XMLWriter(new FileOutputStream(filepath),format);
writer.write(document);
writer.close();
}
}
如果filepath用的是上面写的,测试的对文档的操作到reader.read(new File(filepath));这就停了
估计是