Java - Resource

Java Conceptuel Diagram

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

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

Example

getResourceAsStream

InputStream inputStream = MyClass.class.getResourceAsStream("/myDir/myResource.txt");
// Note that ''getResourceAsStream'' will the load the ''ZipFileSystem''

You can then transform it as a string.

Scanner s = new Scanner(inputStream).useDelimiter("\\A");
String result = s.hasNext() ? s.next() : "";

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

The first backslash is important.

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





Discover More
Card Puncher Data Processing
Database - HyperSQL DataBase (HSQLDB)

HSQLDB is a relational database written in Java. It is used as an embedded database to avoid the requirement of having a third-party database server running separately. for unit and integration...
Card Puncher Data Processing
Maven - Directory Structure (Project)

Maven relies on the Standard Directory Layout A standard project where: the src/main/java directory...



Share this page:
Follow us:
Task Runner