How to package resources in Jar properly

26,908

Mark the resource folder under your project's root folder as a "Source Folder" in Eclipse (right click on the folder, go to "Build Path" > "Use as source folder"). Then read the resources like this:

InputStream is = MyClass.class.getClassLoader().getResourceAsStream(name + ".SOURCE");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = reader.readLine();
Share:
26,908

Related videos on Youtube

UMY
Author by

UMY

Updated on July 09, 2022

Comments

  • UMY
    UMY almost 2 years

    I know that there are other questions out there targeting the same issue but the thing is that the solutions don't work for me. I have a little tool that is supposed to read files I want to have and package as resources and relies on other projects (I am using Eclipse Helios) which I'd love to have as jars instead of single classes.

    As an application within Eclipse I can access my resources via

    String path = MyClass.class.getClassLoader().getResource("resources/" + name + ".SOURCE").getPath();
    System.out.println(path);
    File file = new File(MyClass.class.getClassLoader().getResource("resources/" + name + ".SOURCE").toURI());
    defaultSource = readSOURCEFile(file);
    

    if and only if I place the resources folder under the output path (the compiled sources) NOT if I place it in my src folder.

    When I package the project, resources in the root folder or in the classes folder are not packaged at all. If I have the resources in my src folder it get's packaged under src/resources.

    I use Export - Runnable Jar, what am I doing wrong? If I try with Export - Jar, I can package my sources and resources properly but I have issues with setting the main class and can't execute the jar. The Manifest is correct and the class is there :-(.

    Second problem: In the packaged jar I get the error: URI is not hierarchical (after I moved the resources within the jar manually I could execute the jar)

    Thanks in advance!

    I have linked the sources into the workspace is that an issue?

  • UMY
    UMY over 12 years
    If I do that the resources get packaged without the folder resources directly under the root folder.
  • Abhinav Sarkar
    Abhinav Sarkar over 12 years
    You are right. I changed the code accordingly to remove resources from the resource path. If you want a directory called resources in your jar then create this folder hierarchy: <root>/resources/resources and add <root>/resources to eclipse source path as mentioned above. Also add back resources in the resource path in the code.
  • Chris Cirefice
    Chris Cirefice over 7 years
    This is such a simple thing, but without SO and your amazing answer, I would be fumbling around for so many hours... Thank you!!!!
  • Wolf
    Wolf over 7 years
    Worked like a charm :)