0

I have the following problem: I try to load a file from jar but I have the same file outside situated at the same relative path: "res/rtrconfig" as the file in jar. How can I ignore the outside file and get the jar file path?. I can't delete the outside file because other parts of my code need it. What I've got until now:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
        URL url = loader.getResource(path);
        //check if file is in jar or not
        if (url == null) {
            System.err.println("FATAL: Properties file not found.Stopping the server.");
            System.exit(-1);
        }
        if ( !url.getProtocol().equals("jar")){

            System.err.println("Properties found outside jars.Please delete " + url.getPath() + " and re-start the server");
            System.exit(-1);
        }

This part of code checks if the file is founded in jar or in path. I don't know how to configure URL to look after file in jar before file in path. Thanks for your time.

2
  • What does the above code return? Isn't the resource found inside the jar? If not, what is the value of the path you are passing and the full name of the resource inside the jar?
    – c.s.
    Aug 1, 2013 at 12:47
  • "Properties found outside jars.Please delete " + here is an absolute path + " and re-start the server". res\rtrconfig is the name of the resource
    – nucandrei
    Aug 1, 2013 at 13:03

2 Answers 2

1

You can get all resources

Enumeration<URL> urls = ClassLoader.getSystemClassLoader().getResources(path);

file URL will have "file" protocol

    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        if (url.getProtocol().equals("file")) {
            ...
        }
    }
1
  • Thank you.I was heading that way but I didn't knew what to do with that Enum :)
    – nucandrei
    Aug 1, 2013 at 12:44
0

If you are using spring this will work to get the jar resource file from outside jar.

ClassPathResource resource = new ClassPathResource("schema/feed.xsd");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.