Showing posts with label manifest. Show all posts
Showing posts with label manifest. Show all posts

Friday, March 6, 2009

Reading custom field from Manifest file in JAVA

Hi EveryOne,


If your PM tell you declare a version number for your application.
And if you declared application version number as constant in source code.

Then what happens when your application update and version number should be change?

What will you do, again change in source code, then compile, then create jar etc?

It is not just a case where your constant need to update.

i have a solution.

Just add a field on manifest file. And read these fields from your code.
Here i am putting a example code to do so.

It is very easy. You can read all fields from manifest.

For source code see below.

/*

* Program for reading a field from manifest file

* Copyright 2009 @ yuvadeveloper

* Code By:- Prashant Chandrakar

*

* */

import java.io.*;

import java.util.*;

import java.util.jar.*;

import java.net.*;

public class JarRead

{

public static void main(String[] args) throws Exception

{

new JarRead().call();

}

public void call()

{

try

{

////pass your jar file name which included manifest file

JarFile jf = new JarFile("CDViewer.jar");

////getting manifest file from jar file

Manifest m = jf.getManifest();

////getting all attribute from manifest file

Attributes attr = m.getMainAttributes();

////taking values from manifest file.

////existing field

String SOFTWARE_VERSION = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION); // 2.0

String SOFTWARE_VENDOR = attr.getValue(Attributes.Name.IMPLEMENTATION_VENDOR); // YuvaDevelopers Pvt.Ltd.

String SOFTWARE_VENDOR_TITLE = attr.getValue(Attributes.Name.IMPLEMENTATION_TITLE); // ManifestReader

////custom defined field

String dType = attr.getValue("RunType");

System.out.println(SOFTWARE_VERSION + "\n" + SOFTWARE_VENDOR + "\n" + SOFTWARE_VENDOR_TITLE + "\n" + dType);

}

catch(Exception e)

{

System.out.println(e);

}

}

}

Manifest file:-

Manifest-Version: 1.2
Main-Class: JarRead
Created-By: 1.4 (Sun Microsystems Inc.)
Specification-Title: build57
Specification-Version: 1.0
Specification-Vendor: Sun Microsystems, Inc.
Implementation-Title: Manifest Reader
Implementation-Version: 1.0.0
Implementation-Vendor: YuvaDevlopers Pvt.Ltd.
RunType: Customfield

Just save as manifest.mf file and add while creating jar file.