0

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?

ddd
  • 11
  • 3

3 Answers3

0

To read the file it must be in classpath, you can put the file in the folder containing .class files or add it to the classpath with java -cp option.

angcap
  • 149
  • 2
  • 9
0
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.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • Yes and If I I want put the result into: File f = new File(example.class.getResource(“/graphics/field.txt“)); Is not work in this way? – ddd May 05 '17 at 19:51
  • Added some text. Unfortunately I did not understood your wish to import data into the resources, which are intended as read-only files. Sorry – Joop Eggen May 06 '17 at 10:45
0

The issue is not so much your code, but how you build and package your jar file. You will have to clarify how you are currently building your jar (using ant, maven, eclipse, etc ?).

Many articles will also advise you to separate out your resources from your source code (.java), and many IDE will support this separation direclty by allowing you to mark a folder as a resource folder. Even maven will allow you to customize this.

See following articles:

Community
  • 1
  • 1
YoYo
  • 9,157
  • 8
  • 57
  • 74