提取目标jar文件中的内容到指定目录
jdk为11
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* @author JHL
*/
public class ExtractJarUtil {
public static final String USER_HOME = System.getProperty("user.home") + File.separator;
public static final String SYSTEM_TMP_DIR = System.getProperty("java.io.tmpdir");
public static void extractJar(String jarPath, String destDir) throws IOException {
File dest = new File(destDir);
if (!dest.exists()) {
dest.mkdirs();
}
JarFile jar = new JarFile(jarPath);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.isDirectory()) {
continue;
}
InputStream in = jar.getInputStream(entry);
Path outPath = Paths.get(destDir, entry.getName());
Files.createDirectories(outPath.getParent());
try (FileOutputStream out = new FileOutputStream(outPath.toFile())) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
}
}
}
public static void main(String[] args) throws IOException {
// extractJar("example.jar", System.getProperty("java.io.tmpdir"));
// extractJar("D:\\code\\gitee\\hikvision\\camera\\target\\camera-1.0-SNAPSHOT.jar", System.getProperty("user.home"));
}
}