What path to use to load stuff like images in Java?

Viewed 35

I am having trouble figuring out what to use to load assets such as images. Would I use the full path then at compile time it would get converted? Or would I use relative path?

For example say I load a file with the directory

C:/Users/Jordan/project/assets/file.txt

If I were to package the program as a jar would the file still be loaded on another person's computer? How does this work?

1 Answers

There are two ways to do this:

  1. Package the file as a resource. In this case it would go into the "assets/file.txt" directory of your JAR file, and you would load it with the path "assets/file.txt" (through ClassLoader#getResource(), not through File and related classes).
  2. Don't package the file as a resource. In that case, you'd have to distribute it along with your JAR (for example, in a ZIP file or a MSI installer), it would have to go into the same relative location on the target machine as it is on your local machine and you would load it through a relative path ("assets/file.txt").

Both of these are valid approaches.

Related