Skip to content

Instantly share code, notes, and snippets.

@fliedonion
Last active July 7, 2017 14:24
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 fliedonion/d4b91858832516012c960ee69b4a2328 to your computer and use it in GitHub Desktop.
Save fliedonion/d4b91858832516012c960ee69b4a2328 to your computer and use it in GitHub Desktop.
Get Java version of specified directory.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace CheckJavaVersion {
class Program {
static void Main(string[] args) {
var cjv = new CheckJavaVersion();
var paths = new List<string> {
@"C:\Program Files\Java\jdk1.8.0_91",
@"C:\Program Files\Java\jdk1.8.0_91\jre",
@"C:\Program Files\Java\jdk1.8.0_91\bin",
@"C:\Program Files\Java\jre1.8.0_91\bin",
@"C:\Program Files (x86)\Java\jdk1.7.0_55",
@"J:\opt\JetBrains\IntelliJ IDEA 2016.2.3\jre\jre",
@"D:\usr\local\pleiades_juno\java\6",
@"D:\usr\local\pleiades_juno\java\7",
@"C:\usr\local\pleiades\java\6",
@"C:\pleiades\java\7",
@"C:\Go",
@"c:\windows",
@"c:\nothingdirectory",
@"S:\nothingrive",
};
paths.ForEach(x => {
var result = cjv.GetVersion(x);
if (string.IsNullOrEmpty(result)) {
Console.WriteLine("Can't find");
}
else {
Console.WriteLine(result);
}
});
Console.ReadKey();
}
}
class CheckJavaVersion {
public string GetVersion(string path) {
if (string.IsNullOrEmpty(path)) return null;
if (!Directory.Exists(path)) return null;
var javaPath = "";
if (File.Exists(Path.Combine(path, "java.exe"))) {
javaPath = Path.Combine(path, "java.exe");
}
else if(File.Exists(Path.Combine(path, "bin", "java.exe"))){
javaPath = Path.Combine(path, "bin", "java.exe");
}
if (javaPath == "") return null;
var psi = new ProcessStartInfo(javaPath, "-version");
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
var p = Process.Start(psi);
var stdOut = p.StandardError.ReadLine();
p.StandardError.ReadToEnd();
p.Close();
var m = Regex.Match(stdOut, "^.*?(java|openjdk) version \"([0-9])\\.([0-9]+)(.*?)\".*$");
return m.Groups[2] + "." + m.Groups[3] + ", " + m.Groups[2] + "." + m.Groups[3] + m.Groups[4] + ", " + m.Groups[1];
}
}
}
@fliedonion
Copy link
Author

sample output

1.8, 1.8.0_91, java
1.8, 1.8.0_91, java
1.8, 1.8.0_91, java
1.8, 1.8.0_91, java
1.7, 1.7.0_55, java
1.8, 1.8.0_112-release, openjdk
1.6, 1.6.0_41, java
1.7, 1.7.0_15, java
1.6, 1.6.0_45, java
1.7, 1.7.0_67, java
Can't find
Can't find
Can't find
Can't find

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