java代码打war包
一、 maven依赖
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress -->
<!-- 处理压缩解压 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.9</version>
</dependency>
二、 解压
warPath是war包,unZipPath是生成的目录的名字
/**
* 解压war文件
* @param warPath war文件路径
* @param unZipPath 解压到的路径
*/
public static boolean unZipWar(Path warPath, Path unZipPath) {
String warName = warPath.toFile().getName();
LOGGER.debug("warName: " + warName);
LOGGER.debug("unZipPath: " + unZipPath.toString());
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(warPath.toFile()));
ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(
ArchiveStreamFactory.JAR, bis)) {
if (Files.exists(unZipPath)) {
Files.delete(unZipPath);
}
Files.createDirectories(unZipPath);
JarArchiveEntry entry;
while ((entry = (JarArchiveEntry) ais.getNextEntry()) != null) {
if (entry.isDirectory()) {
Path currentPath = Paths.get(unZipPath.toString(), entry.getName());
if (!Files.exists(currentPath.getParent())) {
Files.createDirectories(currentPath);
} else if (!Files.exists(currentPath)) {
Files.createDirectory(currentPath);
}
} else {
Path currentPath = unZipPath.resolve(entry.getName());
if (!Files.exists(currentPath.getParent())) {
Files.createDirectories(currentPath.getParent());
}
try (OutputStream os = Files.newOutputStream(currentPath)) {
IOUtils.copy(ais, os);
}
}
}
} catch (ArchiveException | IOException e) {
LOGGER.error(ServerMsgConstants.UNPACK_WAR_ERROR + warName, e);
return false;
}
return true;
}
三、 压缩
对 sourceDir目录进行压缩,后缀是.war,生成sourceDir.war文件
/**
* 创建 war 文件
* @param sourceDir
*/
public static boolean zipWar(Path sourceDir) {
sourceDir = sourceDir.toAbsolutePath();
String rootDir = sourceDir.toString();
LOGGER.debug("rootDir: " + rootDir);
if (!StringUtils.endsWithFileSeparator(rootDir)) {
rootDir += File.separator;
}
Path warPath = sourceDir.getParent().resolve(StringUtils.appendWarSuffix(sourceDir.getFileName().toString()));
try (BufferedOutputStream bos = new BufferedOutputStream(Files.newOutputStream(warPath));
ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream(ArchiveStreamFactory.JAR, bos)) {
Iterator<File> files = FileUtils.iterateFiles(sourceDir.toFile(), null, true);
LOGGER.debug("rootDir: " + rootDir);
while (files.hasNext()) {
File file = files.next();
ZipArchiveEntry entry = new ZipArchiveEntry(file, StringUtils.remove(file.getAbsolutePath(), rootDir));
aos.putArchiveEntry(entry);
try (InputStream is = new FileInputStream(file)) {
IOUtils.copy(is, aos);
}
aos.closeArchiveEntry();
}
aos.flush();
} catch (IOException | ArchiveException e) {
LOGGER.error(ServerMsgConstants.PACK_WAR_ERROR, e);
return false;
}
return true;
}