Skip to content

Instantly share code, notes, and snippets.

@parttimenerd
Created January 9, 2026 09:42
Show Gist options
  • Select an option

  • Save parttimenerd/cdd6e5f963c6af180cdee6bbaf6f535a to your computer and use it in GitHub Desktop.

Select an option

Save parttimenerd/cdd6e5f963c6af180cdee6bbaf6f535a to your computer and use it in GitHub Desktop.
Java version detector
#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;
}
@parttimenerd
Copy link
Author

This tool allows you to get the version of a java binary in a Java installation
in around one millisecond instead of > 20ms for java -version.

Compile it via:

g++ -std=c++17 java_version.cpp -o java_version

Then use it via:

./java-version `which java`
# or directly
./java-version java/25-sapmchn/bin/java

License

MIT

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment