# 2.2. Resource接口

位于`org.springframework.core.io.`包中的Spring`Resource`接口旨在成为一个更强大的接口，用于抽象对低级资源的访问。以下清单提供了`Resource`界面的概述。有关详细信息，请参阅 [`Resource`](https://docs.spring.io/spring-framework/docs/5.3.22/javadoc-api/org/springframework/core/io/Resource.html)javadoc。

```java
public interface Resource extends InputStreamSource {

    boolean exists();

    boolean isReadable();

    boolean isOpen();

    boolean isFile();

    URL getURL() throws IOException;

    URI getURI() throws IOException;

    File getFile() throws IOException;

    ReadableByteChannel readableChannel() throws IOException;

    long contentLength() throws IOException;

    long lastModified() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

    String getDescription();
}
```

正如`Resource`接口的定义所示，它扩展了`InputStreamSource` 接口。以下清单显示了`InputStreamSource` 接口的定义：

```java
public interface InputStreamSource {

    InputStream getInputStream() throws IOException;
}
```

`Resource`接口中一些最重要的方法是：

* `getInputStream()`：定位并打开资源，返回一个`InputStream`用于从资源中读取。预计每次调用都会返回一个新的 `InputStream`. 调用者有责任关闭流。
* `exists()`：返回一个`boolean`指示此资源是否实际以物理形式存在的值。
* `isOpen()`：返回一个`boolean`指示此资源是否表示具有打开流的句柄。如果为`true`， 则`InputStream`不能多次读取，必须只读取一次然后关闭以避免资源泄漏。对于所有常用资源实现返回 `false`（`InputStreamResource` 除外）。
* `getDescription()`：返回此资源的描述，用于在使用该资源时输出错误。这通常是完全限定的文件名或资源的实际 URL。

其他方法让您获得表示资源的实际`URL`或`File`对象（如果底层实现兼容并支持该功能）。

`Resource`接口的一些实现还为支持写入的资源实现了扩展 [`WritableResource`](https://docs.spring.io/spring-framework/docs/5.3.22/javadoc-api/org/springframework/core/io/WritableResource.html)接口。

Spring 本身广泛使用`Resource`抽象，在需要资源时作为许多方法签名中的参数类型。某些 Spring API 中的其他方法（例如各种 `ApplicationContext` 实现的构造函数）采用 `String`，该 `String` 以原始或简单的形式用于创建适合该上下文实现的资源，或者通过 `String` 路径上的特殊前缀，让调用者指定必须创建和使用特定的资源实现。

虽然`Resource`接口在 Spring 和 Spring 中被大量使用，但实际上在您自己的代码中将其本身用作通用实用程序类非常方便，用于访问资源，即使您的代码不知道或不关心spring任何其他部分。虽然这会将您的代码与 Spring 耦合，但它实际上只将它耦合到这一小部分实用程序类，它可以作为更强大的替代品，`URL`并且可以被认为等同于您将用于此目的的任何其他库。

`Resource`抽象不会取代功能。它尽可能地包装它。例如，UrlResource 包装 URL 并使用包装的 URL 来完成其工作。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://doc.shiker.tech/spring-he-xin-gong-neng/2.-resources/2.2.-resource-jie-kou.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
