Maven Assembly插件打包tar.gz:如何包含文件夹及所有子目录?
解决maven-assembly-plugin打包指定文件夹及其子内容的问题
我来帮你搞定这个需求!要把目标文件夹及其所有子文件夹、文件都完整包含到tar.gz包里,你只需要在assembly.xml中添加正确的<fileSet>配置段就行。结合你给出的代码片段,我整理了完整可复用的配置示例:
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd"> <id>dist</id> <formats> <format>tar.gz</format> <!-- 明确指定要生成的tar.gz格式 --> </formats> <!-- 核心配置:打包指定文件夹及其所有子内容 --> <fileSets> <fileSet> <!-- 替换成你要打包的本地文件夹路径,比如项目根目录下的src/main/resources/assets --> <directory>${project.basedir}/src/main/resources/assets</directory> <!-- 打包后在tar.gz里的目标位置,比如根目录下的assets文件夹 --> <outputDirectory>assets</outputDirectory> <!-- 递归匹配所有文件和子目录,**/*是关键 --> <includes> <include>**/*</include> </includes> <!-- 可选:设置文件和目录的权限,符合Linux规范 --> <fileMode>0644</fileMode> <directoryMode>0755</directoryMode> </fileSet> </fileSets> </assembly>
关键配置细节说明:
<directory>:必填项,指定你要打包的源文件夹路径,可以用Maven内置变量(比如${project.basedir}代表项目根目录)来避免硬编码路径。<outputDirectory>:可选,控制打包后该文件夹在tar.gz中的位置,如果留空会直接把文件夹内容放到tar包的根目录下。<includes>里的**/*:这是实现递归打包的核心,**表示任意层级的子目录,*表示任意类型的文件,确保所有子内容都被包含。如果需要过滤特定文件,可添加<excludes>标签来排除。<fileMode>和<directoryMode>:可选配置,设置打包后文件和目录的权限,默认值也能满足大部分场景需求。
另外,别忘了在pom.xml中正确关联maven-assembly-plugin和你的assembly.xml文件:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.6.0</version> <!-- 使用最新稳定版本 --> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> <configuration> <descriptors> <!-- 指向你的assembly.xml文件路径 --> <descriptor>src/main/assembly/assembly.xml</descriptor> </descriptors> </configuration> </execution> </executions> </plugin> </plugins> </build>
执行mvn package命令后,就能得到包含指定文件夹所有子内容的tar.gz包了!
内容的提问来源于stack exchange,提问作者G.G.




