Created
October 16, 2021 16:10
-
-
Save jpstotz/84091fd79d1e5682f64aa5daac868363 to your computer and use it in GitHub Desktop.
Check the class file version of all class files within a JAR file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.DataInputStream; | |
import java.util.ArrayList; | |
import java.util.Enumeration; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.TreeMap; | |
import java.util.zip.ZipEntry; | |
import java.util.zip.ZipFile; | |
/** | |
* Check the class file version of all class files within a JAR file | |
* | |
* When execute this program provide the path to the JAR file as argument. | |
*/ | |
public class CheckJarClassVersion { | |
public static void main(String[] args) { | |
Map<Integer, List<String>> map = new TreeMap<>(); | |
try (ZipFile jar = new ZipFile(args[0])) { | |
Enumeration<? extends ZipEntry> entries = jar.entries(); | |
while (entries.hasMoreElements()) { | |
ZipEntry entry = entries.nextElement(); | |
if (!entry.getName().endsWith(".class")) | |
continue; | |
try (DataInputStream in = new DataInputStream(jar.getInputStream(entry))) { | |
int magic = in.readInt(); | |
if (magic != 0xCAFEBABE) { | |
System.out.println("Not a class file - skipping " + entry.getName()); | |
continue; | |
} | |
int classFileVersion = in.readInt(); | |
List<String> files = map.get(classFileVersion); | |
if (files == null) { | |
files = new ArrayList<>(); | |
map.put(classFileVersion, files); | |
} | |
files.add(entry.getName()); | |
} catch (Exception e) { | |
System.err.println("Error reading class " + entry.getName() + ": " + e); | |
} | |
} | |
for (int versionCode : map.keySet()) { | |
List<String> files = map.get(versionCode); | |
System.out.println(String.format("Version of Class File Format: %d (Java %d) - files: %d", versionCode, | |
versionCode - 44, files.size())); | |
// Uncomment to see all files in each category | |
// files.forEach(x -> System.out.println("\t" + x)); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment