import org.apache.logging.log4j.util.Base64Util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class JarFileUtils {
public static void main(String[] args) throws Exception {
String str = "C:\\Users\\lenovo\\Desktop\\testJar\\bytecode.jar";
List<String> list = new ArrayList();
list.add("test\\demo");
list= list.stream().map(x->x.replace("\\","/")).toList();
String s = unCompressProjectJarFile(str, list);
System.out.println("--------------------------------");
System.out.println(s);
}
public static String unCompressProjectJarFile(String filePath, List<String> projectPath) throws Exception {
File file = new File(filePath);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File tempFile : files) {
unCompressProjectJarFile(tempFile.getAbsolutePath(), projectPath);
}
return filePath;
} else {
if (filePath.endsWith(".jar") || filePath.endsWith(".war")) {
JarFile jarFile = new JarFile(filePath);
List<JarEntry> jarEntries = jarFile.stream().toList();
for (JarEntry entry : jarEntries) {
String realName = entry.getRealName();
List<String> list = projectPath.stream().filter(x -> {
return realName.contains(x);
}).toList();
if (!list.isEmpty()) {
String jarUnCompressPath = unCompressJarFile(filePath);
unCompressProjectJarFile(jarUnCompressPath, projectPath);
return jarUnCompressPath;
}
}
}
return "";
}
}
public static String unCompressJarFile(String filePath) throws Exception {
File rawFile = new File(filePath);
String name = rawFile.getName();
name = Base64Util.encode(name);
String rootPath = rawFile.getParent() + File.separator + name + File.separator;
File rootDir = new File(rootPath);
if (!rootDir.exists()) {
rootDir.mkdirs();
}
JarFile jarFile = new JarFile(filePath);
List<JarEntry> jarEntries = jarFile.stream().toList();
for (JarEntry entry : jarEntries) {
String realName = entry.getRealName();
String fileName = rootPath + realName;
File targetFile = new File(fileName);
if (entry.isDirectory()) {
if (!targetFile.exists()) {
targetFile.mkdirs();
}
} else {
InputStream inputStream = jarFile.getInputStream(entry);
FileOutputStream outputStream = new FileOutputStream(targetFile);
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
}
}
}
return rootPath;
}
}