Created
January 4, 2024 20:03
-
-
Save learner-long-life/27556e5212ea01ac56be875a046fe636 to your computer and use it in GitHub Desktop.
How to update a JAR file entry from https://subversivebytes.wordpress.com/2012/10/11/java-programmatically-update-jar-file/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void updateJarFile(File srcJarFile, String targetPackage, File ...filesToAdd) throws IOException { | |
File tmpJarFile = File.createTempFile("tempJar", ".tmp"); | |
JarFile jarFile = new JarFile(srcJarFile); | |
boolean jarUpdated = false; | |
try { | |
JarOutputStream tempJarOutputStream = new JarOutputStream(new FileOutputStream(tmpJarFile)); | |
try { | |
//Added the new files to the jar. | |
for(int i=0; i < filesToAdd.length; i++) { | |
File file = filesToAdd[i]; | |
FileInputStream fis = new FileInputStream(file); | |
try { | |
byte[] buffer = new byte[1024]; | |
int bytesRead = 0; | |
JarEntry entry = new JarEntry(targetPackage+File.separator+file.getName()); | |
tempJarOutputStream.putNextEntry(entry); | |
while((bytesRead = fis.read(buffer)) != -1) { | |
tempJarOutputStream.write(buffer, 0, bytesRead); | |
} | |
//System.out.println(entry.getName() + " added."); | |
} | |
finally { | |
fis.close(); | |
} | |
} | |
//Copy original jar file to the temporary one. | |
Enumeration jarEntries = jarFile.entries(); | |
while(jarEntries.hasMoreElements()) { | |
JarEntry entry = jarEntries.nextElement(); | |
InputStream entryInputStream = jarFile.getInputStream(entry); | |
tempJarOutputStream.putNextEntry(entry); | |
byte[] buffer = new byte[1024]; | |
int bytesRead = 0; | |
while ((bytesRead = entryInputStream.read(buffer)) != -1) { | |
tempJarOutputStream.write(buffer, 0, bytesRead); | |
} | |
} | |
jarUpdated = true; | |
} | |
catch(Exception ex) { | |
ex.printStackTrace(); | |
tempJarOutputStream.putNextEntry(new JarEntry("stub")); | |
} | |
finally { | |
tempJarOutputStream.close(); | |
} | |
} | |
finally { | |
jarFile.close(); | |
//System.out.println(srcJarFile.getAbsolutePath() + " closed."); | |
if (!jarUpdated) { | |
tmpJarFile.delete(); | |
} | |
} | |
if (jarUpdated) { | |
srcJarFile.delete(); | |
tmpJarFile.renameTo(srcJarFile); | |
//System.out.println(srcJarFile.getAbsolutePath() + " updated."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment