0

I need to access to a xsd file that it's inside my jar. My problem is that my classpath is C:\Users\fabio\Documents.

My jar file it's in that path too , so how can I get the file that I need?

I tried File xsdFile=new File(String.valueOf(MigrationsApplication.class.getResource("DBRegister.xsd"))); but got this error message schema_reference.4: Failed to read schema document 'file:/C:/Users/fabio/Documents/null', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.

This is my location of the xsd file I need enter image description here

Fabio
  • 343
  • 1
  • 6
  • 17

1 Answers1

2

MigrationsApplication.class.getResource("DBRegister.xsd")

This part is good.

new File

Nope. File refers to an actual file on your harddisk. And that resource aint one of those. You can't use File here. Period.

There are only two APIs that read resources:

  • Ones that work with InputStream or some other abstracted source concept such as URL. Perhaps in addition (with e.g. overloaded methods) to ones that take in a File, Path or (bad design) String representing a file path.
  • Crap ones you shouldn't be using.

Let's hope you have the first kind of API :)

Then we fix some bugs:

  1. Use getResourceAsStream to get an InputStream, getResource to get a URL. Which one should you use? Well, check the API of where you're passing this resource to. For example, swing's ImageIcon accepts URLs, so you'd use getResource there.
  2. .getResource("DBRegister.xsd") looks for that file in the same place MigrationsApplication.class is located. Which is the wrong path! Your DBRegister.xsd is in the 'root'. Include a slash at the start to resolve relative to root.

Easy enough to take care of it:

try (var in = MigrationsApplication.class.getResourceAsStream("/DBRegister.xsd")) {
   whateverYouArePassingThatFileTo(in);
}

If whateverYouArePassingThatFileTo() doesn't have a variant that takes in an InputStream, delete that library and find a better one.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • 1
    Since the resource is an XSD, I suspect he’ll want to pass the resource URL to [SchemaFactory.newSchema(URL)](https://docs.oracle.com/en/java/javase/16/docs/api/java.xml/javax/xml/validation/SchemaFactory.html#newSchema(java.net.URL)), as in: SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(MigrationsApplication.class.getResource("/DBRegister.xsd")) – VGR Jul 01 '21 at 14:30