Skip to content

Instantly share code, notes, and snippets.

@jpstotz
Created October 16, 2021 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpstotz/84091fd79d1e5682f64aa5daac868363 to your computer and use it in GitHub Desktop.
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
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