Skip to content

Instantly share code, notes, and snippets.

@ajchemist
Created October 25, 2018 02:20
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 ajchemist/947525cb2b0432f248843160a21d67ad to your computer and use it in GitHub Desktop.
Save ajchemist/947525cb2b0432f248843160a21d67ad to your computer and use it in GitHub Desktop.
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