← 中文资源

简体中文版本

getResourceAsStream 资源查找规则

带 / 前缀按 classpath 根解析,不带则自动拼上包名前缀;找不到返回 null 而不是抛异常,先判空再读,try-with-resources 负责关闭。

阅读英文原文

实现说明

getResourceAsStream 资源查找规则的核心是类 BundledConfig。 try-with-resources 会在每条退出路径上自动关闭声明的资源。

使用要点

  • 每一步打印都带着自己的标签:/tokens.txt not found at classpath root、root:、package-local tokens.txt not found。

常见问题

运行「getResourceAsStream 资源查找规则」会打印什么?

运行文件本身,/tokens.txt not found at classpath root、root:、package-local tokens.txt not found 这些前缀各对应一段演示逻辑。

代码示例

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

public class BundledConfig {

    public static void main(String[] args) throws IOException {
        // 绝对路径:以 / 开头,剥掉前缀直接按 classpath 根解析
        try (InputStream root = BundledConfig.class.getResourceAsStream("/tokens.txt")) {
            if (root == null) {
                System.out.println("/tokens.txt not found at classpath root");
            } else {
                System.out.println("root: " + new String(root.readAllBytes(), StandardCharsets.UTF_8));
            }
        }

        // 相对路径:自动拼上类的包名前缀(modified_package_name/name)
        try (InputStream local = BundledConfig.class.getResourceAsStream("tokens.txt")) {
            if (local == null) {
                System.out.println("package-local tokens.txt not found");
            }
        }

        // 资源不存在返回 null 而不是抛异常:先判空再读
        try (InputStream none = BundledConfig.class.getResourceAsStream("/no-such.bin")) {
            System.out.println("missing resource -> " + (none == null ? "null" : "stream"));
        }
    }
}