检查java的class文件版本

直接代码调用对应的方法 checkFilesInDir

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class CheckClassVersion {
    public static void main(String[] args) {
        run();
    }

    private static Map<Integer, String> map = new HashMap<Integer, String>(30);
    private static boolean showAllClassVersion = false;//false:对比版本时只显示版本错误的class
    static {
        JDKVERSION[] values = JDKVERSION.values();
        for (JDKVERSION val : values) {
            map.put(val.getValue(), val.getName());
        }
    }
    
    private static void run(){
        Scanner scanner = new Scanner(System.in);
        do{
            System.out.println("------输入[class文件路径]或[class所在文件夹路径]------q退出");
            String input = scanner.nextLine();
            if("q".equalsIgnoreCase(input)){
                scanner.close();
                break;
            }else{
                System.out.println("==========执行开始==========");
                checkFilesInDir(input);
                System.out.println("==========执行结束==========");
            }
            
        }while(true);
    }
    
    /**
     * 显示文件夹下class文件版本号
     * @param dirPath
     */
    public static void checkFilesInDir(String dirPath) {
        checkFilesInDir(dirPath, null);
    }
    
    /**
     * 检查文件夹下class文件版本号
     * @param dirPath
     * @param jdkVersion 期望class版本号
     */
    public static void checkFilesInDir(String dirPath, JDKVERSION jdkVersion) {
        if(jdkVersion!=null){
            System.out.println("期望class版本号:" + jdkVersion); 
        }
        if (dirPath == null) {
            System.out.println("传入路径为空。");
            return;
        }
        if (dirPath.endsWith("\\")) {
            dirPath = dirPath.replaceAll("\\", "/");
        }

        File path = new File(dirPath);
        if (!path.exists()) {
            System.out.println(dirPath + "路径不存在。");
            return;
        }
        
        if(path.isFile()){
            getFileNameAndCheck(path, jdkVersion);
        } else if(path.isDirectory()){
            File[] files = path.listFiles();
            if (files != null && files.length > 0) {
                for (File file : files) {
                    getFileNameAndCheck(file, jdkVersion);
                }
            }
        }
    }

    /**
     * 检查单个class文件版本
     * 
     * @param file
     * @param checkVersion
     * @return true:版本相同;false:版本不同
     */
    private static boolean check(String file, JDKVERSION jdkVersion) {
        if (!file.endsWith(".class")) {
            return false;
        }
        FileInputStream fis = null;
        byte[] b = null;
        try {
            fis = new FileInputStream(file);
            b = new byte[8];
            try {
                int read = fis.read(b, 0, 8);
                if (read != 8) {
                    System.out.println(" 文件读取错误");
                    return false;
                }

                int fileVersion = parseFile(b);
                if(jdkVersion==null){
                    StringBuffer sb = new StringBuffer();
                    sb.append(file);
                    sb.append(" 文件版本号:");
                    sb.append(map.get(fileVersion));
                    System.out.println(sb.toString()); 
                    return false;
                }
                
                if (jdkVersion.getValue() == fileVersion) {
                    if(showAllClassVersion){
                        StringBuffer sb = new StringBuffer();
                        sb.append(file);
                        sb.append(" 文件版本号:");
                        sb.append(map.get(fileVersion));
                        sb.append(" ------版本正确");
                        System.out.println(sb.toString()); 
                    }
                    return true;
                }else{
                    StringBuffer sb = new StringBuffer();
                    sb.append(file);
                    sb.append(" 文件版本号:");
                    sb.append(map.get(fileVersion));
                    sb.append(" ------版本错误");
                    System.out.println(sb.toString());
                    return false;
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (b != null) {
                b = null;
            }
        }

        return false;
    }

    /**
     * 返回主版本号
     * 
     * @param data
     * @return
     */
    private static int parseFile(byte[] data) {
        StringBuffer sb = new StringBuffer();
        sb.append("魔数(magic):0x");
        sb.append(Integer.toHexString(data[0]).substring(6).toUpperCase());
        sb.append(Integer.toHexString(data[1]).substring(6).toUpperCase());
        sb.append(Integer.toHexString(data[2]).substring(6).toUpperCase());
        sb.append(Integer.toHexString(data[3]).substring(6).toUpperCase());
        sb.append(" 版本号(version):");
        int minor_version = (((int)data[4]) << 8) + data[5];// 次版本号
        int major_version = (((int)data[6]) << 8) + data[7];// 主版本号
        sb.append(major_version);
        sb.append(".");
        sb.append(minor_version);
        // System.out.println(sb.toString());

        return major_version;
    }

    private static void getFileNameAndCheck(File file, JDKVERSION jdkVersion) {
        if (file == null) {
            return;
        }

        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files == null || files.length == 0) {
                return;
            }
            for (File f : files) {
                getFileNameAndCheck(f, jdkVersion);
            }
        } else if (file.isFile()) {
            String fileName = file.getPath();
            
            check(fileName, jdkVersion);
        }
    }

}

/**
 * jdk版本号
 * 
 * @author jinzhm
 *
 */
enum JDKVERSION {
    JDK1(45, "JDK1"), JDK2(46, "JDK2"), JDK3(47, "JDK3"), JDK4(48, "JDK4"), JDK5(49, "JDK5"), JDK6(50, "JDK6"), JDK7(
        51, "JDK7"), JDK8(52, "JDK8"), JDK9(53, "JDK9"), JDK10(54, "JDK10"), JDK11(55, "JDK11"), JDK12(56, "JDK12"),
    JDK13(57, "JDK13"), JDK14(58, "JDK14"), JDK15(59, "JDK15"), JDK16(60, "JDK16"), JDK17(61, "JDK17");

    private int value;
    private String name;

    private JDKVERSION(int value, String name) {
        this.value = value;
        this.name = name;
    }

    public int getValue() {
        return value;
    }

    public String getName() {
        return name;
    }
}

 

 

编译两个版本class,瞎搞个bat执行

目录结构

main

  -jdk6

    -CheckClassVersion.class

    -JDKVERSION.class

  -jdk8

    -CheckClassVersion.class

    -JDKVERSION.class

  -run.bat

 

run.bat执行

@echo off
@REM 编码

set classpath=%~dp0

set VERSION6="1.6.0_21"
for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
@REM    @echo Output: %%g
    set JAVAVER=%%g
)
set JAVAVER=%JAVAVER:"=%
@REM @echo Output: %JAVAVER%

for /f "delims=. tokens=1-3" %%v in ("%JAVAVER%") do (
@REM    @echo Major: %%v
@REM    @echo Minor: %%w
@REM    @echo Build: %%x
    set Major=%%v
    set Minor=%%w
    set Build=%%x
)

set Major=%Major:"=%
set Minor=%Minor:"=%
set jdkv=%Major%_%Minor%

set jdk6=1_6
set jdk8=1_8

echo %jdkv%|findstr %jdk6% >nul &&( goto run1_6)
echo %jdkv%|findstr %jdk8% >nul &&( goto run1_8)

:run1_6
cd /d %JAVA_HOME%\bin
java.exe -classpath %classpath%jdk6\ CheckClassVersion
pause > nul
exit

:run1_8
cd /d %JAVA_HOME%\bin
java.exe -classpath %classpath%jdk8\ CheckClassVersion
pause > nul
exit

 

posted @ 2023-04-21 10:37  新手娃娃菜  阅读(164)  评论(0编辑  收藏  举报