深度技术解析 · 实战案例驱动 · 安全规范保障
在Java开发中,读取jar包里的文件是高频但易被误用的操作。它不同于普通文件系统访问,需通过类加载机制访问嵌入资源。常见场景包括:读取配置文件(如application.properties)、加载模板(如FreeMarker、Thymeleaf模板)、加载资源文件(如SQL脚本、JSON Schema、证书)等。
关键在于:资源文件被打包进jar后,其物理路径不再存在;文件不再是文件系统中的“节点”,而是jar中以ZIP格式存储的条目(Entry)。因此,必须通过ClassLoader或URL机制访问,而非new File(...)。
⚠️ 警示:使用FileInputStream或new File(...)读取jar内资源将导致FileNotFoundException》,这是90%线上问题的根源。
某系统在开发环境(文件系统中资源为真实文件)正常,部署为jar后启动报错:
java.io.FileNotFoundException: classpath:config/app.properties (No such file or directory)
问题代码:
InputStream in = new FileInputStream("config/app.properties");
正确方式应为:
InputStream in = getClass().getClassLoader().getResourceAsStream("config/app.properties");
二者本质差异在于:前者尝试访问文件系统路径;后者通过类路径(Classpath)定位资源,兼容jar、War、模块化结构。
Java中读取jar内文件的主流方式有以下四种,其本质均依赖ClassLoader或Resource抽象层。下表从使用场景、路径要求、返回类型、是否支持写入、兼容性五维度对比:
| 方式 | 调用路径 | 返回类型 | 支持相对路径? | 是否可写入 | 适用范围 |
|---|---|---|---|---|---|
ClassLoader.getResourceAsStream(String) |
绝对路径(从classpath:根开始) |
InputStream |
否(必须以/或无前缀) |
否 | 标准JDK,兼容所有环境 |
Class.getResourceAsStream(String) |
相对路径(相对当前Class所在包)或绝对路径(以/开头) |
InputStream |
是 | 否 | 类内读取(如工具类、主类) |
Resource.openStream() |
classpath:前缀 + 绝对路径 |
InputStream |
否 | 否 | Spring资源抽象(需引入Spring) |
JarURLConnection |
完整jar URL(如jar:file:/app.jar!/path/file) |
InputStream或JarEntry |
否 | 仅读取(可通过JarEntry获取元数据) |
需精确URL,适用于动态扫描 |
所有方案均基于java.util.jar.JarURLConnection实现。以ClassLoader.getResourceAsStream为例:
getResource(name) → 转为URL(如jar:file:/app.jar!/config/app.properties)URL.openConnection() → 返回JarURLConnection实例getInputStream() → 内部打开jar文件流,定位到ZipEntry并返回💡 注意:每次调用均需重新打开jar文件流,因此频繁读取应缓存InputStream或转换为byte[]。
底层源码关键路径:
java.lang.ClassLoader#getResource → sun.misc.Launcher$AppClassLoader#findResource → java.util.jar.JarFile#getEntry
在复杂应用(如OSGi、Tomcat、Spring Boot Fat Jar)中,ClassLoader层级影响资源定位:
rt.jar等核心类库,无法通过getClass().getClassLoader()访问jre/lib/ext目录WebAppClassLoader、Spring Boot的LaunchedURLClassLoader在Spring Boot中,使用getClass().getClassLoader()读取META-INF/resources下的静态资源可能失败,因该路径由WebServerClassLoader管理。此时应改用ServletContext.getResourceAsStream或ResourceLoader。
资源路径书写错误是第二大高频问题,尤其在跨平台部署时。核心规则如下:
/(斜杠),而非\(反斜杠)——即使在Windows系统中/决定相对/绝对语义:Class.getResource("/config/app.properties") = 从classpath根开始Class.getResource("app.properties") = 从当前类所在包路径开始%20),需用java.net.URLDecoder解码⚠️ 危险示例:路径写成"config\\app.properties"在Linux环境100%失败!
动态拼接路径时,避免硬编码斜杠。推荐使用Paths.get(...).toString()或String.format:
String basePath = "config";
String fileName = "app.properties";
String fullPath = basePath + "/" + fileName; // 正确:统一使用/
若需兼容模块化(Java 9+),路径应包含模块名前缀:
// 模块com.example.app中的资源
String path = "com.example.app/config/app.properties";
常见错误:直接用Properties.load(new FileInputStream("config/app.properties"))。
正确方案:
Properties props = new Properties();
try (InputStream in = getClass().getClassLoader().getResourceAsStream("config/app.properties")) {
if (in == null) {
throw new FileNotFoundException("config/app.properties not found in classpath");
}
props.load(in);
String dbUrl = props.getProperty("db.url");
}
增强健壮性:添加默认值与校验:
String dbUrl = props.getProperty("db.url", "jdbc:mysql://localhost:3306/db");
if (dbUrl == null || dbUrl.isEmpty()) {
throw new IllegalStateException("db.url must not be empty");
}
在非Spring环境,手动加载jar内模板:
TemplateEngine engine = new TemplateEngine();
ClasspathTemplateResolver resolver = new ClasspathTemplateResolver();
resolver.setPrefix("templates/");
resolver.setSuffix(".html");
resolver.setTemplateMode(TemplateMode.HTML);
resolver.setCharacterEncoding("UTF-8");
resolver.setCacheable(false); // 开发阶段关闭缓存
engine.setTemplateResolver(resolver);
Context context = new Context();
context.setVariable("title", "用户列表");
String html = engine.process("user-list", context); // 读取templates/user-list.html
若模板路径含中文或特殊字符,需确保jar打包时使用UTF-8编码(Maven插件配置<encoding>UTF-8</encoding>)。
安全敏感操作,需防止路径遍历攻击:
String certPath = "certs/server.crt";
try (InputStream in = getClass().getClassLoader().getResourceAsStream(certPath)) {
if (in == null) {
throw new SecurityException("Certificate not found: " + certPath);
}
CertificateFactory cf = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) cf.generateCertificate(in);
}
关键防护:
request.getParameter("cert"))直接拼接路径/certs/*.crt)通过URLClassLoader扫描jar内所有资源:
URL jarUrl = new File("plugins/example.jar").toURI().toURL();
URLClassLoader classLoader = new URLClassLoader(new URL[]{jarUrl});
Enumeration resources = classLoader.getResources("");
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
String path = url.getPath(); // 如: jar:file:/plugins/example.jar!/META-INF/
if (path.endsWith(".properties")) {
System.out.println("Found: " + path);
}
}
注意:此方式需关闭jar文件锁定(Windows需设置useLibsDir=false),否则后续删除jar失败。
模块化项目中,资源需显式声明在module-info.java中:
module com.example.app {
exports com.example.app.service;
uses com.example.app.spi.Plugin;
provides com.example.app.spi.Plugin with com.example.app.plugin.FilePlugin;
}
读取模块内资源路径需包含模块名:
String path = "com.example.app/config/app.properties";
InputStream in = getClass().getClassLoader().getResourceAsStream(path);
若资源位于非模块化依赖(如第三方jar),路径仍从classpath根开始。
频繁读取jar内资源会导致频繁打开/关闭jar流,引发性能瓶颈。优化策略:
byte[]缓存volatile + double-check保证线程安全示例:缓存模板内容
private static final Map TEMPLATE_CACHE = new ConcurrentHashMap<>();
public byte[] loadTemplate(String name) {
return TEMPLATE_CACHE.computeIfAbsent(name, n -> {
try (InputStream in = getClass().getClassLoader().getResourceAsStream("templates/" + n + ".html")) {
return in.readAllBytes();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
注意:大文件(如10MB+视频)禁止缓存,应流式处理。
| 读取方式 | 100次读取耗时(1KB文件) | 100次读取耗时(1MB文件) | 适用场景 |
|---|---|---|---|
文件系统(FileInputStream) |
~8ms | ~120ms | 资源解压后独立文件 |
JAR流(getResourceAsStream) |
~25ms | ~350ms | 嵌入式资源,零依赖部署 |
| 缓存字节数组 | ~3ms | ~180ms | 小文件高频读取 |
结论:小文件用缓存方案;大文件建议外部化部署(如NFS、S3),jar内仅存元数据。
jar内资源读取存在以下安全风险:
../../../etc/passwd读取系统文件META-INF/maven/pom.xml)防护措施:
SecurityManager)危险代码:
String userInput = request.getParameter("file"); // "/../../../etc/passwd"
String path = "files/" + userInput;
InputStream in = getClass().getClassLoader().getResourceAsStream(path);
修复方案:
public String sanitizeResourcePath(String input) {
String normalized = new File(input).getCanonicalPath();
String base = new File("src/main/resources").getCanonicalPath();
if (!normalized.startsWith(base + File.separator) && !normalized.equals(base)) {
throw new SecurityException("Access denied: " + input);
}
return normalized.replace(base, "").replace(File.separator, "/");
}
注意:此方案需在非jar运行时有效;jar内需改用URL校验(如检查jar:file:/.../files/前缀)。
可能原因:
jar tf your-app.jar)getServletContext().getClassLoader())<resources>配置未包含)诊断步骤:
// 1. 检查资源是否存在
System.out.println("Resource URL: " + getClass().getClassLoader().getResource("config/app.properties"));
// 2. 打印ClassLoader层级
System.out.println("ClassLoader: " + getClass().getClassLoader());
System.out.println("Parent: " + getClass().getClassLoader().getParent());
JAR本身无目录概念,需遍历所有Entry:
URL jarUrl = new File("app.jar").toURI().toURL();
JarURLConnection conn = (JarURLConnection) jarUrl.openConnection();
JarFile jarFile = conn.getJarFile();
Enumeration entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String name = entry.getName();
if (name.startsWith("templates/") && !entry.isDirectory()) {
System.out.println("Found: " + name);
}
}
JAR规范要求路径使用Cp437编码,但现代JDK默认用UTF-8。解决方案:
<encoding>UTF-8</encoding>)new String(entry.getName().getBytes("Cp437"), "UTF-8")转换常见于BOOT-INF/classes/路径问题。正确方式:
@Autowired
private ResourceLoader resourceLoader;
Resource resource = resourceLoader.getResource("classpath:config/app.properties");
try (InputStream in = resource.getInputStream()) {
// 读取
}
或直接使用applicationContext.getResource("classpath:...")。
以下内容与java读取jar包里的文件深度关联,构成完整技术图谱:
ClassLoader是资源加载的核心。其双亲委派模型保证安全性:
findClass,而非loadClass示例:自定义ClassLoader加载jar内资源
class JarClassLoader extends URLClassLoader {
public JarClassLoader(URL[] urls) {
super(urls, ClassLoader.getSystemClassLoader().getParent());
}
}
jar内资源文件编码需与JVM默认一致(通常为UTF-8)。常见问题:
GBK,jar内UTF-8文件读取后中文乱码-Dfile.encoding=UTF-8new InputStreamReader(in, StandardCharsets.UTF_8)Java 9+模块系统中,资源受模块声明约束:
opens包)Module.getResourceAsStream替代ClassLoader可获取模块上下文Module module = getClass().getModule();
InputStream in = module.getResourceAsStream("config/app.properties");
生产环境不推荐将敏感配置(如DB密码)内置jar中。更优实践:
java -jar app.jar --spring.config.location=external.properties安全原则:配置不进包,密钥不硬编码。
Web应用中,jar内静态资源(HTML/CSS/JS)可通过以下方式加速:
gzip on)Cache-Control: max-age=31536000)spring.web.resources.static-locations=classpath:/static/开发阶段需动态加载jar内资源:
常见漏洞:jar内含敏感文件(如.git、credentials)
mvn clean package -DskipTeststrivy --severity HIGH,CRITICAL .jar tf app.jar | grep -i secret为防止资源被篡改,可对jar内资源做哈希校验:
MessageDigest md = MessageDigest.getInstance("SHA-256");
try (InputStream in = getClass().getClassLoader().getResourceAsStream("config/app.properties")) {
byte[] data = in.readAllBytes();
byte[] hash = md.digest(data);
// 与预存hash比对
}
生产环境建议使用数字签名(JAR签名)。
资源加载失败需记录上下文:
logger.warn("Failed to load config/app.properties from classpath. " +
"ClassLoader: {}, Current Thread: {}",
getClass().getClassLoader(),
Thread.currentThread().getName());
结合APM工具(如SkyWalking),可追踪资源加载链路。
兼容Java 8/11/17的资源读取方案:
readAllBytes()(Java 9+)IOUtils.toByteArray(in)(Apache Commons IO)public static byte[] readAllBytes(InputStream in) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[4096];
while ((nRead = in.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
}
ClassLoader.getResourceAsStream成为主流方式,但无统一资源抽象层
Resource接口,统一文件系统、classpath、URL资源访问
Files.readAllBytes简化流读取,但jar内仍需getResourceAsStream
InputStream.readAllBytes正式加入标准库,但模块化后路径规则更严格
ModuleLayer支持动态资源隔离,但jar内资源读取仍是高频痛点
/开头?(绝对/相对需明确)jar tf验证)getClass().getClassLoader())-cp)<resources>配置)opens?| 工具/库 | 用途 | 优势 |
|---|---|---|
| Apache Commons IO | 简化流操作 | IOUtils.toString(in, UTF_8) |
| Guava | 资源加载辅助 | Resources.toString(url, UTF_8) |
| Spring Framework | 统一资源抽象 | ResourceLoader |
| JBoss VFS | 处理嵌套jar(WildFly) | 透明访问嵌套jar |
File操作 → 实际不可写,且路径不适用src/main/resources/... → 实际应去掉src/...前缀资源文件常与依赖管理混淆:
spring-core-5.3.20.jar),通过dependency引入resources目录管理BOOT-INF/lib/或META-INF/lib/,但访问方式不同建议监控以下指标:
云原生时代,资源管理向以下方向演进:
趋势:jar内资源仅保留启动必需项,其余外部化。