gpt4 book ai didi

java - 我在运行 war 时遇到 FileNotFoundException

转载 作者:行者123 更新时间:2023-11-30 07:48:07 25 4
gpt4 key购买 nike

这是我用来访问 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)

附言这 100% 不是文件访问的问题,因为我做了一个生成 JAXB 类的简单项目,从资源文件夹中解码相同的 xml,一切正常。

这是一个项目结构:

enter image description here

最佳答案

您已标记 ,所以我假设您可以使用它。

您的 war 是否在部署后解压(例如通过 Tomcat)?

如果是,

使用 ClassPathResource#getFile()

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

幸运的是,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 - 我在运行 war 时遇到 FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49445042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com