如何读取Maven依赖包中ZIP文件内的JSON文件
解决ZIP依赖中JSON文件的读取问题
问题根源:Maven默认不会将ZIP类型的依赖解压并加入项目的类路径,因此getClass().getResourceAsStream()无法从类路径中找到目标JSON文件。以下是几种可行的解决方案:
方法一:使用Maven依赖插件解压ZIP到类路径
通过maven-dependency-plugin在构建过程中自动将ZIP依赖解压到类路径目录,后续即可直接用类路径读取方法获取文件。
在项目的pom.xml中添加如下插件配置:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>3.6.0</version> <executions> <execution> <id>unpack-zip-dependency</id> <phase>process-resources</phase> <goals> <goal>unpack</goal> </goals> <configuration> <artifactItems> <artifactItem> <groupId>org.foo</groupId> <artifactId>myComponent</artifactId> <version>1.0</version> <type>zip</type> <outputDirectory>${project.build.directory}/classes</outputDirectory> </artifactItem> </artifactItems> </configuration> </execution> </executions> </plugin> </plugins> </build>
配置说明:
- 插件会在
process-resources阶段执行解压操作,将指定ZIP依赖解压到target/classes目录 - 该目录下的文件会自动加入类路径,之后你可以继续使用
getClass().getResourceAsStream("/myFolder/myFile.json")读取文件
方法二:直接读取ZIP包内的文件(无需解压)
如果不想修改构建配置,可以通过代码直接定位到ZIP依赖文件,遍历ZIP条目获取目标JSON的输入流:
import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; public class JsonFileReader { public InputStream getMyFileJsonStream() throws IOException { // 获取ZIP依赖在类路径中的URL URL zipUrl = getClass().getClassLoader().getResource("org/foo/myComponent/1.0/myComponent-1.0.zip"); if (zipUrl == null) { throw new IOException("Failed to locate the ZIP dependency in classpath"); } // 处理不同格式的URL路径 String zipPath = zipUrl.getPath(); if (zipPath.startsWith("file:")) { zipPath = zipPath.substring(5); } if (zipPath.contains("!")) { zipPath = zipPath.split("!")[0]; } // 遍历ZIP条目,找到目标文件 try (ZipFile zipFile = new ZipFile(zipPath)) { Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if ("myFolder/myFile.json".equals(entry.getName())) { return zipFile.getInputStream(entry); } } } throw new IOException("myFolder/myFile.json not found in the ZIP archive"); } }
方法三:将ZIP转为JAR依赖(如果可行)
JAR本质是特殊格式的ZIP,如果该ZIP包的目录结构符合JAR的类路径规范,可以将其重命名为.jar,并修改Maven依赖的type为jar:
<dependency> <groupId>org.foo</groupId> <artifactId>myComponent</artifactId> <version>1.0</version> <type>jar</type> <!-- 将type从zip改为jar --> <scope>compile</scope> <exclusions> <exclusion> <groupId>*</groupId> <artifactId>*</artifactId> </exclusion> </exclusions> </dependency>
修改后,Maven会将其当作普通JAR依赖处理,你可以直接用getClass().getResourceAsStream("/myFolder/myFile.json")读取文件。
内容的提问来源于stack exchange,提问作者Carlos Ruiz
相关产品推荐
相关产品推荐

