Class ResourceUtil

java.lang.Object
com.sure.tool.io.ResourceUtil

public final class ResourceUtil extends Object
资源读取工具,统一支持 classpath、文件系统与 HTTP(S) 资源。

位置解析顺序:

  1. classpath: 前缀:从类路径读取,如 classpath:config/app.properties;
  2. file: 前缀:文件系统 URL,如 file:/tmp/data.txt;
  3. http: / https: 前缀:远程 URL;
  4. 无前缀:先按类路径查找,未找到再按文件系统相对/绝对路径查找。

示例:

byte[] data = ResourceUtil.readBytes("classpath:config/app.properties");
String text = ResourceUtil.readUtf8String("/tmp/data.txt");
boolean found = ResourceUtil.exists("https://example.com/health");

null 语义:位置为 null 或空白串时相关方法返回 null/false(空安全); 需要数据但资源不存在时抛 IllegalArgumentException。

English: Classpath and file-system resource loading helpers.

Since:
1.19.1
Author:
suretool
  • Method Details

    • getResource

      public static URL getResource(String location)
      解析资源位置为 URL。
      Parameters:
      location - 资源位置,可为 null
      Returns:
      资源 URL;未找到或位置为空返回 null
      Throws:
      IllegalArgumentException - 显式 URL 格式非法
    • exists

      public static boolean exists(String location)
      判断资源是否存在。
      Parameters:
      location - 资源位置,可为 null
      Returns:
      存在返回 true
    • getStream

      public static InputStream getStream(String location) throws IOException
      打开资源输入流,调用方负责关闭。
      Parameters:
      location - 资源位置,可为 null
      Returns:
      输入流;资源不存在返回 null
      Throws:
      IOException - 打开资源失败
    • readBytes

      public static byte[] readBytes(String location) throws IOException
      读取资源全部字节。
      Parameters:
      location - 资源位置
      Returns:
      资源字节内容
      Throws:
      IOException - 资源不存在或读取失败
    • readUtf8String

      public static String readUtf8String(String location) throws IOException
      读取资源为 UTF-8 字符串。
      Parameters:
      location - 资源位置
      Returns:
      资源文本
      Throws:
      IOException - 资源不存在或读取失败
    • readString

      public static String readString(String location, Charset charset) throws IOException
      读取资源为字符串。
      Parameters:
      location - 资源位置
      charset - 字符集,null 时使用 UTF-8
      Returns:
      资源文本
      Throws:
      IOException - 资源不存在或读取失败