Thursday, June 24, 2010

Getting the Manifest Version inside a Jar File

/**
*
*/



import java.io.File;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Logger;


/**
* @author Kiran
*
*/


public class JarFileVersionInfoNew {

/**
* A logger for this class.
**/
private static final Logger LOG =
Logger.getLogger(JarFileVersionInfoNew.class.getName());



/**
* Displays the attributes contained in the manifest of one (or
* several jar files...
*
* @param args a list of jar file.
*/
public static void main(String[] args) {
final String path = "C:/Documents and Settings/kkanapar/Workspaces/WSRP/liferay-portal-new/lib/global";
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
System.out.println("Number of files and directories in the file system You gave: " + listOfFiles.length);
for (int i = 0; i < listOfFiles.length; i++) {
String tempFileName = null;
if (listOfFiles[i].isFile()) {
tempFileName = listOfFiles[i].getName();
System.out.println("File " +"-"+i+": "+ tempFileName);
} else if (listOfFiles[i].isDirectory()) {
System.out.println("Directory " +"-"+i+": "+ listOfFiles[i].getName());
}



final File f = new File(path+"\\"+tempFileName);
if (!f.canRead()) {
System.err.println(f.getAbsolutePath()+": no such file");
continue;
}
try {
JarFile jar = new JarFile(f);
final Manifest manifest = jar.getManifest();
final Attributes mattr = manifest.getMainAttributes();
System.out.println(f.getAbsolutePath());
System.out.println("Main attrs: ");
for (Object a : mattr.keySet()) {
System.out.println("\t "+a+": "+mattr.getValue((Name)a));
}


System.out.println("\nReading other attrs:\n");

final Map attrs = manifest.getEntries();
for (String name : attrs.keySet()) {
final Attributes attr = attrs.get(name);
System.out.println(name+": \n");
for (Object a : attr.keySet()) {
System.out.println("\t "+a+": "+attr.getValue((Name)a));
}
}
System.out.println("\n ======================================================================================\n");

} catch (Exception x) {
System.err.println("Failed to read manifest for "+
f.getAbsolutePath()+": "+x);
}
}
}

}

No comments: