Java - Resource

> Procedural Languages > Java

1 - About

A resource abstraction is implemented in Java because a resource could be:

  • in the file system,
  • on any place on the classpath
  • in a jar file
  • or otherwise

3 - Path

  • relative path: They are the default (Resource paths are relative to the location of the class file)
  • absolute path: Use the a slash in your path. It's the 'root' of your resource project
Advertising

4 - Example

4.1 - getResourceAsStream

InputStream stylesource = getClass().getResourceAsStream("/myResource.properties");

From Maven, the root is src/resources in test but also in main. Just put your resource in this directory to avoid problem.

The relative path would only work if the resources are packaged in that class's JAR file because it will create a path as: mypackage/path/ResourceName

4.2 - getResource

URL url = MyClass.class.getResource("/myDir/myResource.ext");

From Maven, the root is src/resources in test but also in main.

The first backslash is important.

lang/java/resource.txt · Last modified: 2019/05/03 14:16 by 172.69.68.67