Created
June 5, 2018 13:50
-
-
Save bitsnaps/f78adb9371e3a8bc029721428e4ea437 to your computer and use it in GitHub Desktop.
Update Jar file by adding new ones with Groovy
This file contains 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
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