本人在开发人员管理系统的时候,写完dao进入Junit测试时出现异常,代码如下:
URL url = XmlUtil.class.getClassLoader().getResource("user.xml") ;
filepath = url.getPath() ;
异常如下:
我是用xml传输数据的,用getPath()获得的xml文件的路径。经过观察可以发现,在getPath()获得的路径中,文件夹名字中含空格的全部用“%”代替。例如文件名为“MyEclipse 202015 CI”用getPath获得的“MyEclipse%202015%20CI”。
解决办法:
URL url = XmlUtil.class.getClassLoader().getResource("user.xml") ;
filepath = url.getPath() ;
try {
filepath = java.net.URLDecoder.decode(filepath,"utf-8");
System.out.println(filepath);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
打印出来的路径为“/C:/Users/Administrator/Workspaces/MyEclipse 2015 CI/day10_1/WebRoot/WEB-INF/classes/user.xml”,这是我们想要的,测试通过。