Created
January 9, 2026 09:42
-
-
Save parttimenerd/cdd6e5f963c6af180cdee6bbaf6f535a to your computer and use it in GitHub Desktop.
Java version detector
This file contains hidden or 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
| #include <filesystem> | |
| #include <fstream> | |
| #include <iostream> | |
| #include <string> | |
| namespace fs = std::filesystem; | |
| int main(int argc, char* argv[]) { | |
| if (argc != 2) { | |
| std::cerr << "Usage: " << argv[0] << " <path-to-bin-java>\n"; | |
| return 1; | |
| } | |
| fs::path javaPath; | |
| try { | |
| javaPath = fs::canonical(argv[1]); | |
| } catch (const fs::filesystem_error& e) { | |
| std::cerr << "Failed to resolve path: " << e.what() << "\n"; | |
| return 1; | |
| } | |
| // Expect .../bin/java | |
| if (javaPath.filename() != "java" || | |
| javaPath.parent_path().filename() != "bin") { | |
| std::cerr << "Path does not end with /bin/java\n"; | |
| return 1; | |
| } | |
| // ../release | |
| fs::path releasePath = javaPath.parent_path().parent_path() / "release"; | |
| std::ifstream file(releasePath); | |
| if (!file) { | |
| std::cerr << "Failed to open " << releasePath << "\n"; | |
| return 1; | |
| } | |
| const std::string key = "JAVA_VERSION=\""; | |
| std::string line; | |
| while (std::getline(file, line)) { | |
| if (line.rfind(key, 0) == 0) { // starts with key | |
| auto start = key.size(); | |
| auto end = line.find('"', start); | |
| if (end != std::string::npos) { | |
| std::cout << line.substr(start, end - start) << "\n"; | |
| return 0; | |
| } | |
| } | |
| } | |
| std::cerr << "JAVA_VERSION not found\n"; | |
| return 1; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This tool allows you to get the version of a
javabinary in a Java installationin around one millisecond instead of > 20ms for
java -version.Compile it via:
g++ -std=c++17 java_version.cpp -o java_versionThen use it via:
License
MIT