Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding JDK path and storing it as a string in Java

Tags:

java

path

I would like to find the JDK path on multiple operating systems.

I'm not sure if there's a nice way of doing this as I've been trying and failing.

For Windows it would be something like this - C:\Program Files\Java\jdk1.7.0_07 or this C:\Program Files(x86)\Java\jdk1.7.0_07

For Linux it would be something like this - /usr/java/jdk1.7.0_07

I want this to work for any version of JDK installed, so the numbers after Java\jdk are irrelevant.

I will be using System.setProperty("java.home", path);

Basically, what I am looking to do is when I run my program, set java.home to be the JDK installed on the current machine, but getting the JDK path is proving very difficult, any solutions?

like image 782
Ciphor Avatar asked Mar 31 '13 02:03

Ciphor


People also ask

How do I find my JDK path?

Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and in system variable try to find JAVA_HOME. This gives me the jdk folder.

How do you give a directory path in Java?

The path for a file can be obtained using the method java. io. File. getPath().

Where do you set the Java_home and JDK bin path locations?

To set JAVA_HOME, do the following: Right click My Computer and select Properties. On the Advanced tab, select Environment Variables, and then edit JAVA_HOME to point to where the JDK software is located, for example, C:\Program Files\Java\jdk1.


2 Answers

You may be able to find the JDK path by looking to see where javac is installed. Assuming that "javac" is within the environment paths of the system then you can retrieve the path by passing "where javac" to code such as the following

public static String getCommandOutput(String command)  {
    String output = null;       //the string to return

    Process process = null;
    BufferedReader reader = null;
    InputStreamReader streamReader = null;
    InputStream stream = null;

    try {
        process = Runtime.getRuntime().exec(command);

        //Get stream of the console running the command
        stream = process.getInputStream();
        streamReader = new InputStreamReader(stream);
        reader = new BufferedReader(streamReader);

        String currentLine = null;  //store current line of output from the cmd
        StringBuilder commandOutput = new StringBuilder();  //build up the output from cmd
        while ((currentLine = reader.readLine()) != null) {
            commandOutput.append(currentLine);
        }

        int returnCode = process.waitFor();
        if (returnCode == 0) {
            output = commandOutput.toString();
        }

    } catch (IOException e) {
        System.err.println("Cannot retrieve output of command");
        System.err.println(e);
        output = null;
    } catch (InterruptedException e) {
        System.err.println("Cannot retrieve output of command");
        System.err.println(e);
    } finally {
        //Close all inputs / readers

        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                System.err.println("Cannot close stream input! " + e);
            }
        } 
        if (streamReader != null) {
            try {
                streamReader.close();
            } catch (IOException e) {
                System.err.println("Cannot close stream input reader! " + e);
            }
        }
        if (reader != null) {
            try {
                streamReader.close();
            } catch (IOException e) {
                System.err.println("Cannot close stream input reader! " + e);
            }
        }
    }
    //Return the output from the command - may be null if an error occured
    return output;
}

The string returned will be the exact location of javac so you may need extra processing to get the directory that javac resides in. You will need to distinguish between Windows and other OS

public static void main(String[] args) {

    //"where" on Windows and "whereis" on Linux/Mac
    if (System.getProperty("os.name").contains("win") || System.getProperty("os.name").contains("Win")) {
        String path = getCommandOutput("where javac");
        if (path == null || path.isEmpty()) {
            System.err.println("There may have been an error processing the command or ");
            System.out.println("JAVAC may not set up to be used from the command line");
            System.out.println("Unable to determine the location of the JDK using the command line");
        } else {
            //Response will be the path including "javac.exe" so need to
            //Get the two directories above that
            File javacFile = new File(path);
            File jdkInstallationDir = javacFile.getParentFile().getParentFile();
            System.out.println("jdk in use at command line is: " + jdkInstallationDir.getPath());
        }//else: path can be found
    } else {
        String response = getCommandOutput("whereis javac");
        if (response == null) {
            System.err.println("There may have been an error processing the command or ");
            System.out.println("JAVAC may not set up to be used from the command line");
            System.out.println("Unable to determine the location of the JDK using the command line");
        } else {
            //The response will be "javac:  /usr ... "
            //so parse from the "/" - if no "/" then there was an error with the command
            int pathStartIndex = response.indexOf('/');
            if (pathStartIndex == -1) {
                System.err.println("There may have been an error processing the command or ");
                System.out.println("JAVAC may not set up to be used from the command line");
                System.out.println("Unable to determine the location of the JDK using the command line");
            } else {
                //Else get the directory that is two above the javac.exe file
                String path = response.substring(pathStartIndex, response.length());
                File javacFile = new File(path);
                File jdkInstallationDir = javacFile.getParentFile().getParentFile();
                System.out.println("jdk in use at command line is: " + jdkInstallationDir.getPath());
            }//else: path found
        }//else: response wasn't null
    }//else: OS is not windows
}//end main method

Note: if the method returns null / error it doesn't mean that javac doesn't exist - it will most likely be that javac isn't within the PATH environment variable on windows and so cannot be found using this method. This isn't likely on Unix as Unix usually adds the jdk/bin directory to the PATH automatically. Also, this will return the javac version currently in use at command line, not necessarily the latest version installed. so if e.g. 7u12 and 7u13 are installed but command prompt is set to use 7u12 then that's the path that will be returned.

Only tested on multiple Windows machines but works fine on them.

Hope this is helpful.

like image 174
tomgeraghty3 Avatar answered Oct 27 '22 19:10

tomgeraghty3


JAVA_HOME is supposed to point to JDK installation path and JRE_HOME to JRE installation path in all OS

like image 44
Evgeniy Dorofeev Avatar answered Oct 27 '22 20:10

Evgeniy Dorofeev