Skip to content

kherge/java.resource

Repository files navigation

Build Status Quality Gate Status

Resource

A library to simplify resource access.

Resource access behaves differently depending on context. For example, resources can be on the file system (during testing) or contained in a JAR (after a build). This library provides a more consistent method of accessing resource by eliminating this distinction.

Resource resource = new Resource(MyClass.class.getClassLoader());

System.out.println(resource.getAsString("hello-world.txt", "utf-8"));
System.out.println(resource.list("path/to/folder"));

Requirements

  • Java 8

Installation

Gradle

compile 'io.herrera.kevin:resource:1.1.0'

Maven

<dependency>
  <groupId>io.herrera.kevin</groupId>
  <artifactId>resource</artifactId>
  <version>1.1.0</version>
</dependency>

Usage

import io.herrera.kevin.resource.Resource;
import java.io.InputStream;
import java.nio.file.Path;

class Example {
    public static void main() {
        try {

            // The manager is created using the desired class loader.
            Resource resource = new Resource(Example.class.getClassLoader());

            // A resource can be retrieved as an InputStream.
            InputStream stream = resource.getAsInputStream("my-resource.txt");

            // A resource can be retrieved as a file path.
            Path path = resource.getAsPath("my-resource.txt");

            // A resource can be retrieved as a string.
            String string = resource.getAsString("my-resource.txt");

            // List resources in a folder.
            List<String> resources = resource.list("path/to/folder");

            // List matching resources in a folder.
            // (This is more performant than using list() and then filtering.)
            List<String> resources = resource.listMatch("path/to/folder", ".+pattern.+");

            // Stream resources in a folder.
            try (Stream<String> resources = resource.stream("path/to/folder")) {
                resources.forEach(name -> System.out.println(resource.getAsString(name));
            }

        } catch (ResourceException exception) {

            // If a resource could not be retrieved or listed, this exception is thrown.
            throw exception;

        }
    }
}

License

This library is made available under the MIT and Apache 2.0 licenses.

About

A library to simplify resource access.

Topics

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages