运行war时出现FileNotFoundException错误

3

这里有一行代码,我用它来访问XML文件。

Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new File(classLoader.getResource("Contacts.xml").getFile())));

运行war文件时,我得到的信息如下:

java.io.FileNotFoundException: file:\D:\apache-tomcat-8.0.50\webapps\pb\WEB-INF\lib\phonebook-server-0.0.1-SNAPSHOT.jar!\Contacts.xml (The filename, directory name, or volume label syntax is incorrect)

附言:这绝对不是文件访问的问题,因为我做了一个简单的项目来生成JAXB类,从资源文件夹解组相同的xml,一切都正常。

下面是该项目的结构:

enter image description here


1
这是一个文件访问问题,因为它不是一个文件。它是来自于 jar 文件内部的资源,无法像文件一样读取。 - M. Deinum
2
将其作为输入流而非文件进行读取。 - M. Deinum
1
@M.Deinum 可以使用Spring的ClassPathResource作为文件进行读取。 - Impulse The Fox
1
不行,因为它不是一个文件,并且在运行时(部署为war时)也会失败。 - M. Deinum
1
确实。我不知道其他的servlet容器,但Tomcat会解压war文件。 - Impulse The Fox
显示剩余4条评论
1个回答

4

你已经打上了的标签,所以我认为你可以使用它。

你的war包是否在部署后(例如通过Tomcat)被解压缩了?

如果是,

请使用ClassPathResource#getFile()

你的问题在于getFile()返回的字符串。它包含一个感叹号(!)和一个file:协议。你可以自己处理所有这些并实现自己的解决方案,但这将是重复造轮子。

幸运的是,Spring有一个org.springframework.core.io.ClassPathResource。要获取文件,只需简单地编写new ClassPathResource("filename").getFile(); 在你的情况下,你需要替换

Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new File(classLoader.getResource("Contacts.xml").getFile())));

使用

Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new ClassPathResource("Contacts.xml").getFile()));

现在你的程序应该在部署和解压缩时也能正常工作。

如果没有(推荐使用,如果不确定,请使用此选项),

你必须使用一个InputStream,因为资源并不存在于文件系统中,而是被打包在归档文件中。

这应该可以工作:

Contacts contactsEntity = (Contacts) um.unmarshal(new InputStreamReader(new ClassPathResource("Contacts.xml").getInputStream()));

(不使用Spring):

Contacts contactsEntity = (Contacts) um.unmarshal(new InputStreamReader(classLoader.getResourceAsStream("Contacts.xml")));

现在我得到了这个错误:java.io.FileNotFoundException: class path resource [Contacts.xml] 无法解析为绝对文件路径,因为它不在文件系统中:jar:file:/D:/apache-tomcat-8.0.50/webapps/pb/WEB-INF/lib/phonebook-server-0.0.1-SNAPSHOT.jar!/Contacts.xml - Antony Prudyus
2
好的.. 我觉得你需要像M.Deinum建议的那样将它读取为InputStream。 - Impulse The Fox
2
谢谢。最终通过这行代码解决了问题:Contacts contactsEntity = (Contacts) um.unmarshal(new InputStreamReader(classLoader.getResourceAsStream("Contacts.xml"))); - Antony Prudyus
非常感谢你,你的回答帮了我很多,在经过两天的搜索后。 - Victor Hanna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接