How to load resources from within a jar file loaded in a java application?How do I efficiently iterate over each entry in a Java Map?Including all the jars in a directory within the Java classpathHow do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I create a Java string from the contents of a file?How do I generate random integers within a specific range in Java?How can I create an executable JAR with dependencies using Maven?How to get an enum value from a string value in Java?How to avoid Java code in JSP files?How do I convert a String to an int in Java?

2019 gold coins to share

TeXForm doesn't work in wolframscript?

empApi with Lightning Web Components?

Do you have to have figures when playing D&D?

I've been given a project I can't complete, what should I do?

What aircraft was used as Air Force One for the flight between Southampton and Shannon?

Why is long-term living in Almost-Earth causing severe health problems?

How to write a convincing religious myth?

Should I put programming books I wrote a few years ago on my resume?

How can I make 12 tone and atonal melodies sound interesting?

Who won a Game of Bar Dice?

Math cases align being colored as a table

Do people with slow metabolism tend to gain weight (fat) if they stop exercising?

Does putting salt first make it easier for attacker to bruteforce the hash?

What would be the way to say "just saying" in German? (Not the literal translation)

Is Lambda Calculus purely syntactic?

Why the output signal of my amplifier is heavily distorted

Possible runaway argument using circuitikz

Solving this logarithmic problem

Printing Pascal’s triangle for n number of rows in Python

Is using 'echo' to display attacker-controlled data on the terminal dangerous?

How do we say "within a kilometer radius spherically"?

Is there a set of positive integers of density 1 which contains no infinite arithmetic progression?

How can one's career as a reviewer be ended?



How to load resources from within a jar file loaded in a java application?


How do I efficiently iterate over each entry in a Java Map?Including all the jars in a directory within the Java classpathHow do I call one constructor from another in Java?How do I read / convert an InputStream into a String in Java?How do I create a Java string from the contents of a file?How do I generate random integers within a specific range in Java?How can I create an executable JAR with dependencies using Maven?How to get an enum value from a string value in Java?How to avoid Java code in JSP files?How do I convert a String to an int in Java?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















So, I have a main application that should load a jar that contains code and other resources (i.e.: jar files, text files, java properties etc.). I use:



JarFile jar = new JarFile(jar);
Enumeration<JarEntry> entries = jar.entries();

int URLsize = 1;
while (entries.hasMoreElements())
if (entries.nextElement().getName().startsWith("foo/bar/foobar"))
URLsize++;

entries = jar.entries();

URL[] urls = new URL[URLsize];
urls[0] = patch.toURI().toURL();

int count = 1;
while (entries.hasMoreElements())

JarEntry nextElement = entries.nextElement();
if (nextElement.getName().startsWith("foo/bar/foobar"))

urls[count] = new URL("jar:file:/"+ jar.getAbsolutePath() + "!/" + nextElement.getName());

count++;




to load the resources of the jar, and an URLClassLoader plus some reflection to get all resources together and execute the jar's main class, like this:



URLClassLoader loader = new URLClassLoader (urls);
Thread.currentThread().setContextClassLoader(loader);

Class<?> jarC = Class.forName ("foo.bar.barfoo.Main", true, loader);
Constructor<?> cons = jarC.getConstructor(String.class, String.class, Properties.class, Properties.class, String[].class);
Object instance = cons.newInstance (systemPath, programPath, config, some_data, args);

Method method = jarC.getMethod ("Main");

method.invoke (instance);


Now the problem is that inside the loaded jar's code when I try to load a bunch of files (resources) from a package inside the jar (e.g.: /foo/bar/foobar) it throws a NullPointerException.



private static InputStream getResourceAsStream(String resource) 
try
return Thread.currentThread().getContextClassLoader().getResource(resource).openStream();
catch (IOException e)
e.printStackTrace();


return null;



That's how I try to get the package that than gets parsed with a BufferedReader and an InputStreamReader to get the names of each resource inside the package.
Okay, maybe a bit too detailed (this is just one way I use the getResourceAsStream method), but I hope I made myself understood, the ContextClassLoader doesn't contain the resources I loaded in the application that runs this jar within itself, so what do I need to do to get those from within the loaded jar?



EDIT: Calling the getResourceAsStream method:



private static List<String> getResourceFiles(String path) throws IOException 
List<String> filenames = new ArrayList<>();

try (
InputStream in = getResourceAsStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in)))
String resource;

while ((resource = br.readLine()) != null)
filenames.add(resource);



return filenames;



And where the getResourceFiles method is called:



List<String> names = Foo.getResourceFiles("/foo/bar/foobar");









share|improve this question






























    0















    So, I have a main application that should load a jar that contains code and other resources (i.e.: jar files, text files, java properties etc.). I use:



    JarFile jar = new JarFile(jar);
    Enumeration<JarEntry> entries = jar.entries();

    int URLsize = 1;
    while (entries.hasMoreElements())
    if (entries.nextElement().getName().startsWith("foo/bar/foobar"))
    URLsize++;

    entries = jar.entries();

    URL[] urls = new URL[URLsize];
    urls[0] = patch.toURI().toURL();

    int count = 1;
    while (entries.hasMoreElements())

    JarEntry nextElement = entries.nextElement();
    if (nextElement.getName().startsWith("foo/bar/foobar"))

    urls[count] = new URL("jar:file:/"+ jar.getAbsolutePath() + "!/" + nextElement.getName());

    count++;




    to load the resources of the jar, and an URLClassLoader plus some reflection to get all resources together and execute the jar's main class, like this:



    URLClassLoader loader = new URLClassLoader (urls);
    Thread.currentThread().setContextClassLoader(loader);

    Class<?> jarC = Class.forName ("foo.bar.barfoo.Main", true, loader);
    Constructor<?> cons = jarC.getConstructor(String.class, String.class, Properties.class, Properties.class, String[].class);
    Object instance = cons.newInstance (systemPath, programPath, config, some_data, args);

    Method method = jarC.getMethod ("Main");

    method.invoke (instance);


    Now the problem is that inside the loaded jar's code when I try to load a bunch of files (resources) from a package inside the jar (e.g.: /foo/bar/foobar) it throws a NullPointerException.



    private static InputStream getResourceAsStream(String resource) 
    try
    return Thread.currentThread().getContextClassLoader().getResource(resource).openStream();
    catch (IOException e)
    e.printStackTrace();


    return null;



    That's how I try to get the package that than gets parsed with a BufferedReader and an InputStreamReader to get the names of each resource inside the package.
    Okay, maybe a bit too detailed (this is just one way I use the getResourceAsStream method), but I hope I made myself understood, the ContextClassLoader doesn't contain the resources I loaded in the application that runs this jar within itself, so what do I need to do to get those from within the loaded jar?



    EDIT: Calling the getResourceAsStream method:



    private static List<String> getResourceFiles(String path) throws IOException 
    List<String> filenames = new ArrayList<>();

    try (
    InputStream in = getResourceAsStream(path);
    BufferedReader br = new BufferedReader(new InputStreamReader(in)))
    String resource;

    while ((resource = br.readLine()) != null)
    filenames.add(resource);



    return filenames;



    And where the getResourceFiles method is called:



    List<String> names = Foo.getResourceFiles("/foo/bar/foobar");









    share|improve this question


























      0












      0








      0








      So, I have a main application that should load a jar that contains code and other resources (i.e.: jar files, text files, java properties etc.). I use:



      JarFile jar = new JarFile(jar);
      Enumeration<JarEntry> entries = jar.entries();

      int URLsize = 1;
      while (entries.hasMoreElements())
      if (entries.nextElement().getName().startsWith("foo/bar/foobar"))
      URLsize++;

      entries = jar.entries();

      URL[] urls = new URL[URLsize];
      urls[0] = patch.toURI().toURL();

      int count = 1;
      while (entries.hasMoreElements())

      JarEntry nextElement = entries.nextElement();
      if (nextElement.getName().startsWith("foo/bar/foobar"))

      urls[count] = new URL("jar:file:/"+ jar.getAbsolutePath() + "!/" + nextElement.getName());

      count++;




      to load the resources of the jar, and an URLClassLoader plus some reflection to get all resources together and execute the jar's main class, like this:



      URLClassLoader loader = new URLClassLoader (urls);
      Thread.currentThread().setContextClassLoader(loader);

      Class<?> jarC = Class.forName ("foo.bar.barfoo.Main", true, loader);
      Constructor<?> cons = jarC.getConstructor(String.class, String.class, Properties.class, Properties.class, String[].class);
      Object instance = cons.newInstance (systemPath, programPath, config, some_data, args);

      Method method = jarC.getMethod ("Main");

      method.invoke (instance);


      Now the problem is that inside the loaded jar's code when I try to load a bunch of files (resources) from a package inside the jar (e.g.: /foo/bar/foobar) it throws a NullPointerException.



      private static InputStream getResourceAsStream(String resource) 
      try
      return Thread.currentThread().getContextClassLoader().getResource(resource).openStream();
      catch (IOException e)
      e.printStackTrace();


      return null;



      That's how I try to get the package that than gets parsed with a BufferedReader and an InputStreamReader to get the names of each resource inside the package.
      Okay, maybe a bit too detailed (this is just one way I use the getResourceAsStream method), but I hope I made myself understood, the ContextClassLoader doesn't contain the resources I loaded in the application that runs this jar within itself, so what do I need to do to get those from within the loaded jar?



      EDIT: Calling the getResourceAsStream method:



      private static List<String> getResourceFiles(String path) throws IOException 
      List<String> filenames = new ArrayList<>();

      try (
      InputStream in = getResourceAsStream(path);
      BufferedReader br = new BufferedReader(new InputStreamReader(in)))
      String resource;

      while ((resource = br.readLine()) != null)
      filenames.add(resource);



      return filenames;



      And where the getResourceFiles method is called:



      List<String> names = Foo.getResourceFiles("/foo/bar/foobar");









      share|improve this question
















      So, I have a main application that should load a jar that contains code and other resources (i.e.: jar files, text files, java properties etc.). I use:



      JarFile jar = new JarFile(jar);
      Enumeration<JarEntry> entries = jar.entries();

      int URLsize = 1;
      while (entries.hasMoreElements())
      if (entries.nextElement().getName().startsWith("foo/bar/foobar"))
      URLsize++;

      entries = jar.entries();

      URL[] urls = new URL[URLsize];
      urls[0] = patch.toURI().toURL();

      int count = 1;
      while (entries.hasMoreElements())

      JarEntry nextElement = entries.nextElement();
      if (nextElement.getName().startsWith("foo/bar/foobar"))

      urls[count] = new URL("jar:file:/"+ jar.getAbsolutePath() + "!/" + nextElement.getName());

      count++;




      to load the resources of the jar, and an URLClassLoader plus some reflection to get all resources together and execute the jar's main class, like this:



      URLClassLoader loader = new URLClassLoader (urls);
      Thread.currentThread().setContextClassLoader(loader);

      Class<?> jarC = Class.forName ("foo.bar.barfoo.Main", true, loader);
      Constructor<?> cons = jarC.getConstructor(String.class, String.class, Properties.class, Properties.class, String[].class);
      Object instance = cons.newInstance (systemPath, programPath, config, some_data, args);

      Method method = jarC.getMethod ("Main");

      method.invoke (instance);


      Now the problem is that inside the loaded jar's code when I try to load a bunch of files (resources) from a package inside the jar (e.g.: /foo/bar/foobar) it throws a NullPointerException.



      private static InputStream getResourceAsStream(String resource) 
      try
      return Thread.currentThread().getContextClassLoader().getResource(resource).openStream();
      catch (IOException e)
      e.printStackTrace();


      return null;



      That's how I try to get the package that than gets parsed with a BufferedReader and an InputStreamReader to get the names of each resource inside the package.
      Okay, maybe a bit too detailed (this is just one way I use the getResourceAsStream method), but I hope I made myself understood, the ContextClassLoader doesn't contain the resources I loaded in the application that runs this jar within itself, so what do I need to do to get those from within the loaded jar?



      EDIT: Calling the getResourceAsStream method:



      private static List<String> getResourceFiles(String path) throws IOException 
      List<String> filenames = new ArrayList<>();

      try (
      InputStream in = getResourceAsStream(path);
      BufferedReader br = new BufferedReader(new InputStreamReader(in)))
      String resource;

      while ((resource = br.readLine()) != null)
      filenames.add(resource);



      return filenames;



      And where the getResourceFiles method is called:



      List<String> names = Foo.getResourceFiles("/foo/bar/foobar");






      java






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 24 at 21:27







      Martin McNamee

















      asked Mar 24 at 20:53









      Martin McNameeMartin McNamee

      112




      112






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Why do you even do all this? Why not just add URL to JAR to the URLClassLoader?



          E.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL());


          Also you should probably make that URLClassLoader have your current classloader as parent, e.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL(), Thread.currentThread().getContextClassLoader());





          share|improve this answer























          • Still giving me a NullPointerException in the same manner.

            – Martin McNamee
            Mar 24 at 21:19












          • Since I don't see any calls to getResourceAsStream in the code you've posted I can't say for sure what is the culprit. Maybe you just provide a bad name of a resource. Can you show the code that actually calls getResourceAsStream?

            – mvmn
            Mar 24 at 21:20











          • It's quite an inception, I'll summarize it in a second and I'll edit the post

            – Martin McNamee
            Mar 24 at 21:22











          • I doubt I call the wrong resource since I tried getting the file in the main application and it works with that ContextLoader.

            – Martin McNamee
            Mar 24 at 21:23











          • I added the code

            – Martin McNamee
            Mar 24 at 21:27











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328467%2fhow-to-load-resources-from-within-a-jar-file-loaded-in-a-java-application%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Why do you even do all this? Why not just add URL to JAR to the URLClassLoader?



          E.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL());


          Also you should probably make that URLClassLoader have your current classloader as parent, e.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL(), Thread.currentThread().getContextClassLoader());





          share|improve this answer























          • Still giving me a NullPointerException in the same manner.

            – Martin McNamee
            Mar 24 at 21:19












          • Since I don't see any calls to getResourceAsStream in the code you've posted I can't say for sure what is the culprit. Maybe you just provide a bad name of a resource. Can you show the code that actually calls getResourceAsStream?

            – mvmn
            Mar 24 at 21:20











          • It's quite an inception, I'll summarize it in a second and I'll edit the post

            – Martin McNamee
            Mar 24 at 21:22











          • I doubt I call the wrong resource since I tried getting the file in the main application and it works with that ContextLoader.

            – Martin McNamee
            Mar 24 at 21:23











          • I added the code

            – Martin McNamee
            Mar 24 at 21:27















          1














          Why do you even do all this? Why not just add URL to JAR to the URLClassLoader?



          E.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL());


          Also you should probably make that URLClassLoader have your current classloader as parent, e.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL(), Thread.currentThread().getContextClassLoader());





          share|improve this answer























          • Still giving me a NullPointerException in the same manner.

            – Martin McNamee
            Mar 24 at 21:19












          • Since I don't see any calls to getResourceAsStream in the code you've posted I can't say for sure what is the culprit. Maybe you just provide a bad name of a resource. Can you show the code that actually calls getResourceAsStream?

            – mvmn
            Mar 24 at 21:20











          • It's quite an inception, I'll summarize it in a second and I'll edit the post

            – Martin McNamee
            Mar 24 at 21:22











          • I doubt I call the wrong resource since I tried getting the file in the main application and it works with that ContextLoader.

            – Martin McNamee
            Mar 24 at 21:23











          • I added the code

            – Martin McNamee
            Mar 24 at 21:27













          1












          1








          1







          Why do you even do all this? Why not just add URL to JAR to the URLClassLoader?



          E.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL());


          Also you should probably make that URLClassLoader have your current classloader as parent, e.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL(), Thread.currentThread().getContextClassLoader());





          share|improve this answer













          Why do you even do all this? Why not just add URL to JAR to the URLClassLoader?



          E.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL());


          Also you should probably make that URLClassLoader have your current classloader as parent, e.g.



          URLClassLoader loader = new URLClassLoader(new File(jar).toURI().toURL(), Thread.currentThread().getContextClassLoader());






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 24 at 21:01









          mvmnmvmn

          1,9041625




          1,9041625












          • Still giving me a NullPointerException in the same manner.

            – Martin McNamee
            Mar 24 at 21:19












          • Since I don't see any calls to getResourceAsStream in the code you've posted I can't say for sure what is the culprit. Maybe you just provide a bad name of a resource. Can you show the code that actually calls getResourceAsStream?

            – mvmn
            Mar 24 at 21:20











          • It's quite an inception, I'll summarize it in a second and I'll edit the post

            – Martin McNamee
            Mar 24 at 21:22











          • I doubt I call the wrong resource since I tried getting the file in the main application and it works with that ContextLoader.

            – Martin McNamee
            Mar 24 at 21:23











          • I added the code

            – Martin McNamee
            Mar 24 at 21:27

















          • Still giving me a NullPointerException in the same manner.

            – Martin McNamee
            Mar 24 at 21:19












          • Since I don't see any calls to getResourceAsStream in the code you've posted I can't say for sure what is the culprit. Maybe you just provide a bad name of a resource. Can you show the code that actually calls getResourceAsStream?

            – mvmn
            Mar 24 at 21:20











          • It's quite an inception, I'll summarize it in a second and I'll edit the post

            – Martin McNamee
            Mar 24 at 21:22











          • I doubt I call the wrong resource since I tried getting the file in the main application and it works with that ContextLoader.

            – Martin McNamee
            Mar 24 at 21:23











          • I added the code

            – Martin McNamee
            Mar 24 at 21:27
















          Still giving me a NullPointerException in the same manner.

          – Martin McNamee
          Mar 24 at 21:19






          Still giving me a NullPointerException in the same manner.

          – Martin McNamee
          Mar 24 at 21:19














          Since I don't see any calls to getResourceAsStream in the code you've posted I can't say for sure what is the culprit. Maybe you just provide a bad name of a resource. Can you show the code that actually calls getResourceAsStream?

          – mvmn
          Mar 24 at 21:20





          Since I don't see any calls to getResourceAsStream in the code you've posted I can't say for sure what is the culprit. Maybe you just provide a bad name of a resource. Can you show the code that actually calls getResourceAsStream?

          – mvmn
          Mar 24 at 21:20













          It's quite an inception, I'll summarize it in a second and I'll edit the post

          – Martin McNamee
          Mar 24 at 21:22





          It's quite an inception, I'll summarize it in a second and I'll edit the post

          – Martin McNamee
          Mar 24 at 21:22













          I doubt I call the wrong resource since I tried getting the file in the main application and it works with that ContextLoader.

          – Martin McNamee
          Mar 24 at 21:23





          I doubt I call the wrong resource since I tried getting the file in the main application and it works with that ContextLoader.

          – Martin McNamee
          Mar 24 at 21:23













          I added the code

          – Martin McNamee
          Mar 24 at 21:27





          I added the code

          – Martin McNamee
          Mar 24 at 21:27



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55328467%2fhow-to-load-resources-from-within-a-jar-file-loaded-in-a-java-application%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

          Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript