天天看點

識别jar的編譯JDK版本

解壓jar,擷取xxx.calss檔案

dos指令行javap -verbose classname

import java.io.InputStream;
import java.io.PrintWriter;

public class CMD指令 {
    public static void main(String[] args) {
        String filePath = "D:/git/new_baiwang/sdk-java/sdk-java/target/classes/com/baiwang/bop/Constants.class";
        docmd(filePath);
    }

    static void docmd(String filePath) {
        String[] command = { "cmd", };
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(command);
            new Thread(new SyncPipe(p.getInputStream())).start();
            new Thread(new SyncPipe(p.getErrorStream())).start();
            PrintWriter stdin = new PrintWriter(p.getOutputStream());
            String ml = "javap -verbose " + filePath;
            stdin.println(ml);
            stdin.close();
        } catch (Exception e) {
            throw new RuntimeException("編譯出現錯誤:" + e.getMessage());
        }
    }
}

class SyncPipe implements Runnable {

    private final InputStream istrm_;

    public SyncPipe(InputStream istrm) {
        istrm_ = istrm;
    }

    public void run() {
        try {
            final byte[] buffer = new byte[10240];
            StringBuffer sbf = new StringBuffer();
            for (int length = 0; (length = istrm_.read(buffer)) != -1;) {
                sbf.append(new String(buffer, 0, length));
            }
            String msg = sbf.toString();
            if (msg.length() > 10) {
                if (msg.contains("major version: 50")) {
                    System.out.println("編譯的JDK版本是1.6");
                } else if (msg.contains("major version: 51")) {
                    System.out.println("編譯的JDK版本是1.7");
                } else if (msg.contains("major version: 52")) {
                    System.out.println("編譯的JDK版本是1.8");
                } else {
                    System.err.println("運作錯誤,未知版本!");
                    System.out.println(msg);
                }

            } else {
                System.err.println("運作錯誤,沒有想要的資訊!");
            }
        } catch (Exception e) {
            throw new RuntimeException("處理指令出現錯誤:" + e.getMessage());
        }
    }
}