Java Programming

jar file의 manifest 내역 수정

tomato13 2009. 7. 3. 14:28

import java.io.*;

import java.util.*;

import java.util.jar.*;

import java.util.zip.*;


public class CreateJarFile2 {


private static Manifest getManifestFile(JarFile jarFile) throws IOException {

JarEntry je = jarFile.getJarEntry("META-INF/MANIFEST.MF");

if (je != null) {

Enumeration entries = jarFile.entries();

while (entries.hasMoreElements()) {

je = (JarEntry) entries.nextElement();

if ("META-INF/MANIFEST.MF".equalsIgnoreCase(je.getName())) {

break;

} else {

je = null;

}

}

}


// create the manifest object

Manifest manifest = new Manifest();


if (je != null) {

manifest.read(jarFile.getInputStream(je));

}


return manifest;

}

private static void updateManifest(Manifest a_manifest) {

Attributes l_attributes = a_manifest.getMainAttributes();

String l_str = l_attributes.getValue("Import-Package");

l_str += ", Java.util.jar";

l_attributes.put(new Attributes.Name("Import-Package"), l_str);

}


protected void createJarArchive(File a_inJar, File a_outJar) {

try{

JarFile inJar = new JarFile(a_inJar);

OutputStream fout = new FileOutputStream(a_outJar);

Manifest l_manifest = getManifestFile(inJar);

updateManifest(l_manifest);

JarOutputStream out = new JarOutputStream(fout, l_manifest);


byte[] buf = new byte[1024];

int available;

String l_fileName = null;

for (Enumeration entries = inJar.entries(); entries.hasMoreElements();) {

JarEntry entry = (JarEntry) entries.nextElement();

l_fileName = entry.getName();

System.out.println(l_fileName);

if(l_fileName.equals("META-INF/MANIFEST.MF")) {

continue;

}

InputStream in = inJar.getInputStream(entry);

try {

JarEntry newEntry = (JarEntry) entry.clone();

newEntry.setCompressedSize(-1);

out.putNextEntry(newEntry);

while ((available = in.read(buf)) != -1) {

out.write(buf, 0, available);

}

out.closeEntry();

} catch (ZipException ex) {

ex.printStackTrace();

return;

} finally {

out.closeEntry();

}

}

out.close();

} catch(IOException ex) {

ex.printStackTrace();

}

System.out.println("Completed");

}

}