问题
Here is a code line, which I use to access xml file.
Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new File(classLoader.getResource("Contacts.xml").getFile())));
Here is what I get while running a 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)
P.S. It is 100% not an issue with file access, because I made a simple project which generates JAXB classes, unmarshals the same xml from resources folder and everything works fine.
Here is a structure of project:
回答1:
You've tagged spring, so I assume you can use it.
Does your war get unpacked after deployment (e.g. by Tomcat)?
If yes,
Use ClassPathResource#getFile()
Your problem is the String that gets returned by getFile()
. It contains an exclamation mark (!
) and a file:
protocol. You could handle all that yourself and implement your own solution for this, but this would be reinventing the wheel.
Fortunately, Spring has a org.springframework.core.io.ClassPathResource
. To get the file, simple write new ClassPathResource("filename").getFile();
In your case, you need to replace
Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new File(classLoader.getResource("Contacts.xml").getFile())));
with
Contacts contactsEntity = (Contacts) um.unmarshal(new FileReader(new ClassPathResource("Contacts.xml").getFile()));
Now your program should also work when it's deployed and unpacked.
If no (recommended, use this if you're not sure),
You have to use an InputStream
, as the resource doesn't exist as a file on the filesystem, but is rather packed inside of an archive.
This should work:
Contacts contactsEntity = (Contacts) um.unmarshal(new InputStreamReader(new ClassPathResource("Contacts.xml").getInputStream()));
(without Spring):
Contacts contactsEntity = (Contacts) um.unmarshal(new InputStreamReader(classLoader.getResourceAsStream("Contacts.xml")));
来源:https://stackoverflow.com/questions/49445042/im-getting-filenotfoundexception-while-running-a-war