overview

Origin

In Hutool, “Resource” is an abstract concept referring to any data storage location. Why provide such an abstract interface?

When writing code, we often need to read various types of data, such as configuration files, text contents, images, or any binary streams. To account for all possible data sources, we would have to create numerous overloaded methods like this:

read(File file){...}

read(InputStream in){...}

read(byte[] bytes){...}

read(URL url){...}

This would make the code cumbersome and difficult to search for API specifications. Regardless of the source of the data, our ultimate goal is usually to obtain a byte array or a String from it. Therefore, we can abstract a Resource interface to simplify the code:

read(Resource resource){...}
```Users only need to provide an implementation of Resource.

## Definition

Often, we need to obtain a stream from a resource (getStream), obtain a Reader to read text (getReader), or read text directly (readStr). Therefore, we define the Resource interface as follows:

```java
public interface Resource {
    String getName();
    URL getUrl();
    InputStream getStream();
    BufferedReader getReader(Charset charset);
    String readStr(Charset charset);
}

For a detailed definition of Resource, see: Resource.java

With the definition of Resource, we can predefine some specific resources:

  • BytesResource: read resources from a byte array
  • InputStreamResource: read resources from an input stream
  • StringResource: read resources from a String
  • UrlResource: read resources from a URL
  • FileResource: read resources from a file
  • ClassPathResource: read resources from the classpath (under src/resources)
  • WebAppResource: read resources from web root
  • MultiResource: mix resources from multiple sources
  • MultiFileResource: mix resources from multiple files

We can also implement the Resource interface ourselves based on specific business needs to complete custom resource reading.

To facilitate resource lookup, you can use the ResourceUtil tool to quickly obtain the resources you need.