Identify JDK version from Java

Asked

Viewed 604 times

6

I am creating an IDE and when the user presses to run the code I do the following:

try {
    File file = new File(arquivoSelecionado.nome);
    try {
        FileWriter fw = new FileWriter(file);
        fw.append(code.getText());  
        fw.close();

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
    Runtime.getRuntime().exec("C:\\Program Files\\Java\\jdk1.8.0_31\\bin\\javac "+file.getName());
    Thread.sleep(2000);
    Process pro = Runtime.getRuntime().exec("cmd /c start java "+file.getName().replaceAll(".java", ""));   

} catch (Exception e1) {
    e1.printStackTrace();
}

only that as it is possible to see I am putting a fixed path to the jdk folder, in this case the version is the one that is in my computer, the problem is that when the jdk version is different from the one that is in the fixed path it does not run the terminal running the program

what I wanted to know is if there is any way to identify the version of jdk that the IDE is running on

  • 2

    The ideal would be to check the java environment variable and so know the JDK installation path

  • %JAVA_HOME% bin java if JAVA_HOME variable exists

1 answer

3

Perhaps a more efficient way is to inspect the JAVA_HOME environment variable:

String javaHome = System.getenv("JAVA_HOME");

To String that returns from this method brings various information, among them, the path in which the compiler is installed.

Just note the fact that if the computer running your program does not have Java installed, the variable javaHome will be void.

  • 4

    It is not reliable, perhaps portable. I do not believe that on *Nix systems when installing Java this environment variable is filled. There is also the case that you may have multiple Javas installed on the machine, but the environment variable is unique; this response does not allow you to distinguish which of the installed Javas is actually running a program

  • 1

    @Jeffersonquesado Nothing is 100% guaranteed. If the target computer of your application does not have Java installed, no solution proposed will be satisfactory, be it environment variable, be it searching installation folders etc. As for the environment variable it also occurs, and is populated, in *Nix environments, like mine, where I tested the code before creating the answer.

  • Java is aware of itself. You may require it to answer what it knows about itself, which is different from asking for an environment variable. And also increases the reliability of this solution

Browser other questions tagged

You are not signed in. Login or sign up in order to post.