Skip to content

Instantly share code, notes, and snippets.

@bitsnaps
Created June 5, 2018 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bitsnaps/f78adb9371e3a8bc029721428e4ea437 to your computer and use it in GitHub Desktop.
Save bitsnaps/f78adb9371e3a8bc029721428e4ea437 to your computer and use it in GitHub Desktop.
Update Jar file by adding new ones with Groovy
import java.util.jar.*
def outputFile = new File("path/to/mylib/MyLib.jar")
def newFile1 = new File("path/to/new/file/NewClass1.class")
def newFile2 = new File("path/to/new/file/NewClass2.class")
updateJarFile(outputFile, newFile1, newFile2)
def updateJarFile(File jarFile, File... files){
def tmpFile = File.createTempFile('tempJar', '.tmp')
def jarTemp = new JarOutputStream(new FileOutputStream(tmpFile))
JarFile outputJar = new JarFile(jarFile)
boolean jarUpdated = false
try {
for (File f in files){
def entry = new JarEntry(f.name)
jarTemp.putNextEntry(entry)
f.eachByte{def buf ->
jarTemp.write(buf)
}
jarTemp.closeEntry()
}
// Copy original jar file to the temporary one.
def jarEntries = outputJar.entries()
for (JarEntry entry in jarEntries) {
jarTemp.putNextEntry(entry)
outputJar.getInputStream(entry).eachByte { def buf ->
jarTemp.write(buf)
}
}
jarUpdated = true
} catch (Exception e){
println("ERROR: ${e.message}")
} finally {
outputJar.close()
jarTemp.close()
if (!jarUpdated) {
tmpFile.delete()
}
}
if (jarUpdated){
jarFile.delete()
tmpFile.renameTo(jarFile)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment