getResourceAsStream Absolute And Package Lookup
Class.getResourceAsStream strips a leading slash for classpath-root lookup, prepends the package for relative names, and returns null for missing resources.
Code
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"));
}
}
}How it works
Structurally, expect the class BundledConfig and nothing else.
Resources are declared in a try-with-resources header, so they close on every exit path without a finally block.
Points of care
- The language toolchain itself is the only prerequisite.
Applying it to real inputs
Look for the /tokens.txt not found at classpath root, root:, package-local tokens.txt not found prefixes during the file’s run; they match each line of output to the step that emitted it.
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does getResourceAsStream Absolute And Package Lookup print when run?
- Invoke the file as-is — the `/tokens.txt not found at classpath root`, `root:`, `package-local tokens.txt not found` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.