補丁總是會一遍又一遍的打,越打越多
有時候,就擔心有人不小心把高版本的class打到低版本jre啟動並執行環境中
簡單寫了點代碼,檢查檔案夾中class的版本號碼
package org.wee.cv;import java.io.File;import java.io.FileInputStream;public class ClassVersion {/** * 檢查class檔案的版本號碼 * @param classFile * @return * 傳回值為:JDK1.4 JDK1.5 ... 或者unknown * @throws Exception */public static String checkClassVersion(File classFile) throws Exception{byte[] data = new byte[8];FileInputStream in = new FileInputStream(classFile);//讀取檔案前8位元組//實際上版本號碼寫在第4-7位元組上(從第0位元組開始算)in.read(data, 0, 8);in.close();//計算出class檔案的主次版本號碼int minor_version = (((int)data[4])<<8)+data[5];int major_version = (((int)data[6])<<8)+data[7];return translateVersionToJDK(major_version);}/** * 根據主要版本號,轉換成JDK版本 * 48是JDK1.4,49是JDK1.5,依次類推 * @param major_version * @return */public static String translateVersionToJDK(final int major_version){switch(major_version){case 48:return "JDK1.4";case 49:return "JDK1.5";case 50:return "JDK1.6";case 51:return "JDK1.7";default:return "unknown";}}}
package org.wee.cv;import java.io.File;import java.util.ArrayList;import java.util.HashMap;import java.util.List;public class BatchClassVersionCheck {public static void main(String[] args) {try {BatchClassVersionCheck bcvc = new BatchClassVersionCheck();HashMap<String,List<String>> versionMap = bcvc.getDirectoryClassVersionInfo(new File("D:/test"));for (String version : versionMap.keySet()){System.out.println("version:" + version);List<String> list = versionMap.get(version);for (String file : list){System.out.println(file);}}} catch (Exception e) {e.printStackTrace();}}//儲存檔案夾中的class檔案版本資訊//key是版本號碼//value是對應檔案的絕對路徑private HashMap<String,List<String>> classVersionInfoMap;/** * 擷取檔案夾中class類的版本資訊 * @param dir * @return * @throws Exception */public HashMap<String,List<String>> getDirectoryClassVersionInfo(File dir) throws Exception{classVersionInfoMap = new HashMap<String,List<String>>();searchClass(dir);return classVersionInfoMap;}/** * 遞迴方法 * 搜尋當前檔案夾下的class檔案,並計算版本資訊,儲存在map中 * 當搜尋到檔案夾時,遞迴搜尋 * @param dir * @throws Exception */protected void searchClass(File dir) throws Exception{File[] childFiles = dir.listFiles();for (File childFile : childFiles){if (childFile.isDirectory()){//遞迴搜尋子檔案夾searchClass(childFile);} else{if (childFile.getName().toLowerCase().endsWith(".class")){//搜尋出class檔案//將版本資訊記錄在map中putVersionInfo(ClassVersion.checkClassVersion(childFile), childFile.getAbsolutePath());}}}}/** * 將版本資訊記錄在map中 * @param version * @param absolutePath */private void putVersionInfo(String version,String absolutePath){List<String> list = null;if (classVersionInfoMap.containsKey(version)){list = classVersionInfoMap.get(version);} else{list = new ArrayList<String>();}list.add(absolutePath);classVersionInfoMap.put(version, list);}}