Class ResourceUtil
java.lang.Object
com.sure.tool.io.ResourceUtil
资源读取工具,统一支持 classpath、文件系统与 HTTP(S) 资源。
位置解析顺序:
classpath:前缀:从类路径读取,如classpath:config/app.properties;file:前缀:文件系统 URL,如file:/tmp/data.txt;http:/https:前缀:远程 URL;- 无前缀:先按类路径查找,未找到再按文件系统相对/绝对路径查找。
示例:
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 Summary
Modifier and TypeMethodDescriptionstatic boolean判断资源是否存在。static URLgetResource(String location) 解析资源位置为 URL。static InputStream打开资源输入流,调用方负责关闭。static byte[]读取资源全部字节。static StringreadString(String location, Charset charset) 读取资源为字符串。static StringreadUtf8String(String location) 读取资源为 UTF-8 字符串。
-
Method Details
-
getResource
解析资源位置为 URL。- Parameters:
location- 资源位置,可为null- Returns:
- 资源 URL;未找到或位置为空返回
null - Throws:
IllegalArgumentException- 显式 URL 格式非法
-
exists
判断资源是否存在。- Parameters:
location- 资源位置,可为null- Returns:
- 存在返回
true
-
getStream
打开资源输入流,调用方负责关闭。- Parameters:
location- 资源位置,可为null- Returns:
- 输入流;资源不存在返回
null - Throws:
IOException- 打开资源失败
-
readBytes
读取资源全部字节。- Parameters:
location- 资源位置- Returns:
- 资源字节内容
- Throws:
IOException- 资源不存在或读取失败
-
readUtf8String
读取资源为 UTF-8 字符串。- Parameters:
location- 资源位置- Returns:
- 资源文本
- Throws:
IOException- 资源不存在或读取失败
-
readString
读取资源为字符串。- Parameters:
location- 资源位置charset- 字符集,null时使用 UTF-8- Returns:
- 资源文本
- Throws:
IOException- 资源不存在或读取失败
-