0

I am trying to read an xsd file to validate schema.

My schema is in location x/y/z/test.xsd

My class reading this file is also in x/y/z/ReadSchema.java

Both there are packaged in my jar.

I am trying to read this file in ReadSchema.java like below where name is test.xsd But url is returned as null?

Anything I am doing wrong here ?

  private static URL getURLForName(String name) 
  {
      ClassLoader cl = Thread.currentThread().getContextClassLoader();

      URL url = cl.getResource(name);
      return url;
  }
bash.d
  • 13,029
  • 3
  • 29
  • 42
constantlearner
  • 5,157
  • 7
  • 42
  • 64

2 Answers2

2

the name you are using is wrong. keep in mind that:

getClass().getResource();

takes a name relative to the class, while

getClass().getClassLoader().getResource();

takes an absolute path.

EDIT: why i call it an absolute path

so, if your file is in yourjar.jar!x/y/z.txt and your class is x.y.Klass

then you could go for:

getClass().getResource("z.txt");

OR you could do:

getClass().getClassLoader().getResource("/x/y/z.txt");
rmalchow
  • 2,689
  • 18
  • 31
1

Nothing wrong, but the test.xsd must be in your claspath. If it works in Eclipse and not in the jar, it mean that your MANIFEST.MF is not correct. Try to add the following line in the manifest and create the jar again :

Manifest-Version: 1.0
Class-Path: . 

Here is the code one of my program :

URL config = SnapshotMigrationMain.class.getResource("/config_migration/log4jconfig.properties");

Of course you have to export your file in the jar or in a subdirectory relative to your jar.
With my example :
migration.jar
/config_migration/log4jConfig.properties

mki
  • 635
  • 3
  • 10