最近在训练web的三层开发模式,写了一个小程序,为了模拟数据库,用了xml来进行存放数据,因此需要将xml文件装载到内存中去,代码如下
private static String fileName; static { fileName=XmlUtils.class.getClassLoader().getResource("user.xml").getPath(); }
采用上面的方法进行获取该文件的物理路径。
一运行出现了下面的错误
java.lang.RuntimeException: org.dom4j.DocumentException:
D:\Workspaces\MyEclipse%208.6\UserModel\WebRoot\WEB-INF\classes\user.xml (系统找不到指定的路径。)
Nested exception: D:\Workspaces\MyEclipse%208.6\UserModel\WebRoot\WEB-INF\classes\user.xml (系统找不到指定的路径。)
将fileName内容输出,发现有个地方很特别,那就是%20,进入路径一看,原来我的workspace中存在一个空格。这导致错误。
下面来自http://www.cumt.org/blog/493里的内容:
"经过一番调查,原来是这是 Java 的一个历史悠久的 bug:
Bug ID: 4466485 getClass( ).getResource( ).getFile( ) returns file name with %20
此 bug 于 2001年6月被提出来,2002年11月最终关闭。
没有修复的原因是这样做会导致兼容性问题。
官方给出的解决方法是采用URI类再把它解码出来。
URI uri = new URI(url.toString()); FileInputStream fis = new FileInputStream(uri.getPath());
而这个bug是当初为了修复另一个 bug 的时候引入的:
Bug ID: 4359123 NoClassDefFoundError if ‘#’ anywhere in path。
我们最终决定不用这个拐弯抹角的方法,干脆采用下面几种办法直接取得 Stream。
ClassLoader.getResourceAsStream ("some/pkg/resource.properties"); Class.getResourceAsStream ("/some/pkg/resource.properties"); ResourceBundle.getBundle ("some.pkg.resource");
"
经过上面的内容进行修改,就正常了。
private static String fileName; static { URI uri; try { uri = new URI(XmlUtils.class.getClassLoader().getResource("user.xml").toString()); fileName = uri.getPath(); } catch (URISyntaxException e) { throw new RuntimeException(e); } }
类.class.getClassLoader().getResourceAsStream("user.xml")也可以进行读取文件,但有一点不适合用它,就是当我们的资源位于服务器上的时候,一旦服务器的资源修改后,不能读取到最新的内容,因为类只装载一次。所以先得到需要先得到路径,在进行读取内容。
log4j用于读取.xml文件的出现了错误,类加载器.getResource("user.xml").getPath()返回路径空格变成了%20,布布扣,bubuko.com
log4j用于读取.xml文件的出现了错误,类加载器.getResource("user.xml").getPath()返回路径空格变成了%20
原文:http://www.cnblogs.com/shinycan/p/3577418.html