0

In Java, I am trying to follow the convention of putting my resource files into src/main/resources.

I am having trouble accessing the file, I can get it to work from either the IDE or running from CLI (JAR), but never both.

What is the best way of getting the full path to my file so I can access it from either a JAR or the IDE?

jim
  • 8,670
  • 15
  • 78
  • 149
  • Possible duplicate of [Cannot load properties file from resources directory](http://stackoverflow.com/questions/20348657/cannot-load-properties-file-from-resources-directory) – Seelenvirtuose Dec 02 '15 at 12:12
  • I know, I know, I need to show code, but I have tried loads of stuff and don't have a coherent sample right now. Surely whoever has the right answer knows off the top of their head. – jim Dec 02 '15 at 12:12
  • `this.getClass().getResource("/MyFont.ttf").toExternalForm()` - where `MyFont.ttf` is in your resources folder which is marked as a `Resources Root` in your IDE. – showp1984 Dec 02 '15 at 12:13

1 Answers1

1

Are you using maven? This convention is for maven projects, is the default resources folder, and maven by default will locate it and put into the jar package root folder, so the resources will be available in classptah from the jar

If you are not using maven, this is useless and you have to manually put that folder into the classpath.

Once the folder is in classpath, you can access to resources with

MyClass.class.getResource(your resource name);
Puce
  • 37,247
  • 13
  • 80
  • 152
Francisco Hernandez
  • 2,378
  • 14
  • 18
  • I would recommend to use `MyClass.class.getResource()`, as `this.getClass().getResource()` might result in unexpected behavior for subclasses in different packages. – Puce Dec 02 '15 at 12:21