Stefan Stefan - 2 years ago 107
Java Question

Loading XSD Schema within JAR by using Resource fails

within my jar I am providing my xsd Schema file, ie following structure:

- myschema.xsd

I can verify the file is present at root level inside the JAR when I unzip it.

I am adding the xsd Schema to the SchemaFactory in the following way:

public void loadXSDSchema() throws InitializationException {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
xsdSchema = sf.newSchema(new File(getClass().getClassLoader().getResource(XSD_SCHEMA_FILE).getFile()));
} catch (SAXException e) {
throw new InitializationException(ApiExceptionId.INIT_XSD_SCHEMA, e);

Unfortunately it is not working in the produced JAR file - I am getting a FileNotFoundException:

Caused by: D:\dev\myjar.jar!\myschema.xsd (Die Syntax fâ–’r den Dateinamen, Verzeichnisnamen oder die Datentrâ–’gerbezeichnung ist falsch)

I thought I did know that you need to read it as a Resource when it's packaged inside a jar but reality shows me I seem to be doing something wrong.

Any hints on what I am missing?

Answer Source

You can not get it as a file since it is not a file. It is an entry in your jar file. Files are operating system objects, and from OS point of view the jar file is the file. Although you can get an InputStream via ClassLoader and you can read the content of it via this InputStream.

Schema xsdSchema = sf.newSchema( new StreamSource(ClassLoader.getSystemResourceAsStream("shema.xsd")));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download