Indigo
Indigo

Reputation: 2997

Get file from another package on different directory level

This problem might have been answered before but I can't seem to make it work. Tried several different previously asked questions and answers.

I have an XML schema file in resource package, and need to get it as a File object from another package called ui.

It must the problem with setting relative path here, but I can't figure out how to fix it.

Class pacakge: com/abc/ui/myClass.java

Resource package: com/abc/resources/schema/XMLSchema.xsd

Sample Code:

    File schemaFile = null;
    try {
        schemaFile = new File(getClass().getClassLoader().getResource("../resources/schema/XMLSchema.xsd").getFile());
    } catch (Exception e) {
        e.printStackTrace();
    }

and/or

    File schemaFile = null;
    try {
        schemaFile = new File(getClass().getResource("../resources/schema/XMLSchema.xsd").getFile());
    } catch (Exception e) {
        e.printStackTrace();
    }

No matter what I try, it keeps throwing null value.

Update: Snap Shots: Class View

Class Package List

Error View

Any solutions to this.

Upvotes: 2

Views: 6809

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

There are two ways of using resources, via the class, or via the class loader.

The class:

SomeClass.class.getResource("/com/abc/resources/schema/XMLSchema.xsd")

The class loader

getClass().getClassLoader().getResource("com/abc/resources/schema/XMLSchema.xsd")

The difference is easy to see: the class loader uses absolute paths as it searches the class paths, several jars.

The class's getResource must start with a slash for absolute paths, and is relative to the package (directory) of the class. Because of inheritance getClass() might point to a child class package, so be careful there.

In your case try the more direct (jar limited) getClass().getResource. I would use an absolute path.

Upvotes: 4

Related Questions