最近遇到java获取DLL文件版本的问题,本来想通过JNI直接调用C++获取版本号,但是程序运行环境部是在windows下面,会导致迁移到LINUX下也无法运行,后来在网上找了很久也没发现问题解决方案,索性就自己研究了下DLL文件内部,代码如下:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class T {
    public static void main(String[] args) throws Exception{
        String filePath = "C:\\WINDOWS\\twain_32.dll";
        File file = new File(filePath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String s = "F i l e V e r s i o n";
        byte[] b = s.getBytes();
        for (int i = 0; i < b.length; i++) {
            if(b[i] == 32){
                b[i] = 0;
            }
        }
        String str = new String(b);
          
        byte[] data = null;
          
        while(reader.ready()){
            String line = reader.readLine();
            int index = line.indexOf(str);
            if(index > 0){
                int len = index + str.length() + 5;
                String sb = line.substring(len,len+16);
                data = sb.getBytes();
                break;
            }
        }
          
        int version1 = getVersion(data, 0, 1);
        int version2 = getVersion(data, 3, 5);
        int version3 = getVersion(data, 7, 9);
        int version4 = getVersion(data, 11, 15);
          
          
        String version = version1 + "." + version2 + "." + version3 + "." + version4;
          
        System.out.println(version);
        System.out.println(new String(data));
    }
      
    public static int getVersion(byte[] data,int start,int end){
        int version = 0;
        int len = end-start;
        byte[] d = new byte[len];
        for (int i = start,j=0; i < end; i++,j++) {
            d[j] = data[i];
        }
        version = Integer.parseInt(new String(d).trim());
        return version;
    }
}