Java I';我在运行war时遇到FileNotFoundException
这里是一个代码行,我使用它来访问xml文件Java I';我在运行war时遇到FileNotFoundException,java,spring,Java,Spring,这里是一个代码行,我使用它来访问xml文件 Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new File(classLoader.getResource("Contacts.xml").getFile()))); 以下是我在进行战争时得到的信息: java.io.FileNotFoundException: file:\D:\apache-tomcat-8.0.50\webapps\pb\WEB-INF\li
Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new File(classLoader.getResource("Contacts.xml").getFile())));
以下是我在进行战争时得到的信息:
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)
另外,这100%不是文件访问的问题,因为我做了一个简单的项目,它生成JAXB类,从resources文件夹中解压相同的xml,并且一切正常
以下是项目的结构:
您已经标记了,所以我想您可以使用它
您的war是否在部署后(例如,通过Tomcat)打开包装
如果是,
使用ClassPathResource\getFile()
您的问题是getFile()
返回的字符串。它包含一个感叹号(!
)和一个文件:
协议。您可以自己处理所有这些问题,并为此实现自己的解决方案,但这将是对轮子的重新发明
幸运的是,Spring有一个org.springframework.core.io.ClassPathResource
。要获取文件,只需编写newclasspathResource(“filename”).getFile()代码>在您的情况下,您需要替换
Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new File(classLoader.getResource("Contacts.xml").getFile())));
与
现在,您的程序在部署和解包时也应该可以工作
如果没有(推荐,如果您不确定,请使用此选项),
您必须使用InputStream
,因为资源在文件系统中不是作为文件存在的,而是打包在存档中
这应该起作用:
Contacts contactsEntity = (Contacts) um.unmarshal(new InputStreamReader(new ClassPathResource("Contacts.xml").getInputStream()));
(无弹簧):
这是一个文件访问问题,因为它不是一个文件。它是jar文件中的一个资源,不能作为文件读取。将其作为输入流而不是文件读取。@M.Deinum它可以使用Spring的ClassPathResource作为文件读取。不,它不能,因为它不是文件,并且在运行时也会失败(当部署为war时)。但到目前为止,我已经多次使用它,当在Tomcat上部署为war时,它可以工作吗?现在我知道:java.io.FileNotFoundException:类路径资源[Contacts.xml]无法解析为绝对文件路径,因为它不在文件系统中:jar:file:/D:/apache-Tomcat-8.0.50/webapps/pb/WEB-INF/lib/phonebook-server-0.0.1-SNAPSHOT.jar/Contacts.xml
OK。。我想你需要按照M.Deinum的建议把它作为输入流来读。谢谢。它最后使用这行代码:Contacts contactsEntity=(Contacts)um.unmarshal(新的InputStreamReader(classLoader.getResourceAsStream(“Contacts.xml”))代码>谢谢谢谢,经过两天的搜索,你的回答帮助我分配了
Contacts contactsEntity = (Contacts) um.unmarshal(new InputStreamReader(new ClassPathResource("Contacts.xml").getInputStream()));
Contacts contactsEntity = (Contacts) um.unmarshal(new InputStreamReader(classLoader.getResourceAsStream("Contacts.xml")));