Search code examples
javajarclassloader

How import a file in a jar?


I have this project that it has this structure

Home
 graphics
    field.txt
    example.java

I need to load field.txt in my example.java in jar and I use:

getClass().getClassLoader().getResource("field.txt").toUri();

but this code it give me "Null Pointer exception" .Anyone can help me?


Solution

  • example.class.getResource(“/graphics/field.txt“);
    

    The class should belong to the same jar. For Class.getResource a relative “field.txt“ is possible (same package). With ClassLoader an absolute path for all classpaths is sought: “graphics/field.txt“.

    To immediately read (never write) use getResourceAsStream or the URI of the getResource. One can use a Path on the URI. Files.copy(...).


    One cannot at least should not) write a resource file (as it can reside in a jar jar:file://...; and jar might even be sealed; and resources might be cached by the jvm). Keep it as read-only template. Never File.

    One technique is to create an application named directory in System.getProperty("user.home") and copy the template there.