Hi,
below is the code which I'm using to update a jar, unfortunately it is not updating the jar file which is in use by some program. I mean the jar itself has this code to update it's own file. The code is working if I want to update another jar file which is not in use.
An I doing it right?
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;
//updateJarFile1( srcJarFile, targetPackage, filesToAdd);
String name ="";
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];
JOptionPane.showMessageDialog(null,filesToAdd[i]);
name = targetPackage+"/"+file.getName();
FileInputStream fis = new FileInputStream(file);
try {
byte[] buffer = new byte[1024];
int bytesRead = 0;
JarEntry entry = new JarEntry(name);
tempJarOutputStream.putNextEntry(entry);
while((bytesRead = fis.read(buffer)) != -1) {
tempJarOutputStream.write(buffer, 0, bytesRead);
}
System.out.println(entry.getName() + " added.");
}
finally {
fis.close();
}
}
Enumeration jarEntries = jarFile.entries();
while(jarEntries.hasMoreElements()) {
JarEntry entry = (JarEntry) jarEntries.nextElement();
// JOptionPane.showMessageDialog(null,entry.getName().toString()+ " fadsfanb.");
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) {
JOptionPane.showMessageDialog(null,ex.toString()+ " gvfdag.");
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.");
}
}