Get file or product version of a program using JNA (Windows) Tag(s): JNA


Windows only
File or product version information can be embedded in an executable file as special attributes. To retrieve these infos from Java, we can use JNA.

This HowTo will extract the file and product versions of javaws.exe. On my installation, the values are :

import java.io.File;

import com.sun.jna.Pointer;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.VerRsrc;
import com.sun.jna.platform.win32.Version;
import com.sun.jna.platform.win32.WinBase;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;

public class FileVersionInfoUsingJNA  {

    // https://github.com/twall/jna#readme
    //  you need 2 jars : jna-3.5.1.jar and platform-3.5.1.jar

    public static void main(String ... args) {

        File fileToCheck = new File("C:\\Program Files (x86)\\Java\\jre7\\bin\\javaws.exe");
        short[] rtnData = new short[4];

        int infoSize =
                Version.INSTANCE.GetFileVersionInfoSize(fileToCheck.getAbsolutePath(), null);
        Pointer buffer = Kernel32.INSTANCE.LocalAlloc(WinBase.LMEM_ZEROINIT, infoSize);

        try {
            Version.INSTANCE.GetFileVersionInfo(fileToCheck.getAbsolutePath(), 0, infoSize, buffer);
            IntByReference outputSize = new IntByReference();
            PointerByReference pointer = new PointerByReference();
            Version.INSTANCE.VerQueryValue(buffer, "\\", pointer, outputSize);
            VerRsrc.VS_FIXEDFILEINFO fileInfoStructure = new VerRsrc.VS_FIXEDFILEINFO(pointer.getValue());

            // file version
            rtnData[0] = (short) (fileInfoStructure.dwFileVersionMS.longValue() >> 16);
            rtnData[1] = (short) (fileInfoStructure.dwFileVersionMS.longValue() & 0xffff);
            rtnData[2] = (short) (fileInfoStructure.dwFileVersionLS.longValue() >> 16);
            rtnData[3] = (short) (fileInfoStructure.dwFileVersionLS.longValue() & 0xffff);

            dump(rtnData);
            /*  output :
              10
              55
              2
              14
            */

            // product version
            rtnData[0] = (short) (fileInfoStructure.dwProductVersionMS.longValue() >> 16);
            rtnData[1] = (short) (fileInfoStructure.dwProductVersionMS.longValue() & 0xffff);
            rtnData[2] = (short) (fileInfoStructure.dwProductVersionLS.longValue() >> 16);
            rtnData[3] = (short) (fileInfoStructure.dwProductVersionLS.longValue() & 0xffff);

            dump(rtnData);
            /*  output :
             7
             0
             550
             14
             */
        }
        finally  {
            Kernel32.INSTANCE.GlobalFree(buffer);
        }
    }

    public static void dump(short [] data) {
        for (int i = 0; i < data.length; i++) {
            System.out.println(data[i]);
        }
    }

}


blog comments powered by Disqus