#include "stdafx.h"
#include <windows.h>
#include <string>
#include<fstream>
#include<iostream>
#ifndef MAX_PATH
#define MAX_PATH 256
#endif
bool checkJavaRuntimeVersion() {
STARTUPINFOA si;
PROCESS_INFORMATION pi;
size_t sizeOfStartupInfo = sizeof(STARTUPINFO);
ZeroMemory(&si, sizeOfStartupInfo);
si.cb = sizeOfStartupInfo;
SECURITY_ATTRIBUTES sa = { sizeof(sa) }; // Open files in inheritable mode
sa.bInheritHandle = TRUE; // Allow inheritance
sa.lpSecurityDescriptor = NULL; // Handles to the child process
si.dwFlags = STARTF_USESTDHANDLES;
const std::string DEFAULT_TEMP_FILE_NAME = "temp_file.txt";
char buffer[MAX_PATH];
char tempPathBuffer[MAX_PATH];
GetTempPathA(MAX_PATH, tempPathBuffer);
std::string file_name;
if ( GetTempFileNameA(tempPathBuffer, "some_random_prefix", 0, buffer) != 0 ) {
file_name = std::string(buffer);
} else {
file_name = DEFAULT_TEMP_FILE_NAME;
}
si.hStdError = CreateFileA(file_name.c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, 0, NULL);
si.hStdOutput = CreateFileA(file_name.c_str(), GENERIC_WRITE, FILE_SHARE_READ, &sa, CREATE_ALWAYS, 0, NULL);
if (si.hStdOutput == NULL) {
MessageBoxA(NULL, "Error checking for the installed Java Virtual Machine, operation aborted", "Launching", MB_ICONERROR | MB_OK);
return false;
}
if (!CreateProcessA(NULL, "java -version", NULL, NULL, true, 0, NULL, NULL, &si, &pi)) {
MessageBoxA(NULL, "It appears that neither you have the Java Virtual Machine installed on your system nor its properly configured", "Launching", MB_ICONERROR | MB_OK);
return false;
}
WaitForSingleObject( pi.hProcess, INFINITE );
if( si.hStdError ) {
CloseHandle( si.hStdError );
}
if( si.hStdOutput ) {
CloseHandle( si.hStdOutput );
}
// "Parse" the txt file
std::ifstream ifs(file_name.c_str());
std::string line;
int versionIndex = 0;
int value[2];
value[0] = value[1] = 0;
while (std::getline(ifs, line)) {
const std::string JAVA_VERSION_STRING = "java version ";
size_t index = line.find(JAVA_VERSION_STRING.c_str());
if (index != std::string::npos) {
// get either the 1.X.X or 2.X.X
std::string version = line.substr(JAVA_VERSION_STRING.size());
std::string::iterator ite = version.begin();
std::string::iterator end = version.end();
std::string tmp = "";
for (; ite != end; ++ite) {
char c = *ite;
if (isdigit(c)) {
tmp += c;
} else if (c == '.') {
value[versionIndex] = atoi(tmp.c_str());
versionIndex++;
tmp = "";
// If we have, version, major and minor, then another set of digits is unnecessary
if (versionIndex == 2)
break;
}
}
std::cout << "detected java version: " << (value[0]) << ", " << (value[1]) << std::endl;
}
}
// Delete the temp file
DeleteFileA(file_name.c_str());
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
checkJavaRuntimeVersion();
return 0;
}windows下检测java版本号的源代码
最新推荐文章于 2024-08-13 16:00:05 发布
本文介绍了一种通过创建临时文件并使用Java命令来检测已安装Java运行时版本的方法。该程序能在Windows环境下运行,通过解析命令输出来获取Java版本号。
2157

被折叠的 条评论
为什么被折叠?



