Finding a JDK path and saving it as a string in Java

I would like to find the JDK path for several operating systems.

I am not sure if there is a good way to do this, as I tried and failed.

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

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

I want this to work for any version of the JDK, so the numbers after Java \ jdk don't matter.

I'll use System.setProperty("java.home", path);

Basically, what I want to do is when I run my program, install java.home as the JDK installed on the current machine, but getting the JDK path is very difficult, any solutions?

+5
source share
14 answers

JDK, , javac. , "javac" , , " javac" , ,

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;
}

javac, , , javac. Windows

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

: null/error, , javac - , , javac PATH Windows . Unix, Unix jdk/bin PATH. , javac, , . , , , 7u12 7u13, 7u12, , .

Windows, .

, .

+7

JAVA_HOME JDK JRE_HOME JRE

+2

, .

public class Main implements Serializable{
    public static void main(String[] args) {
        System.out.println(System.getenv("JAVA_HOME"));
    }
}

C:\Program Files\Java\jdk1.7.0 /usr/java/jdk1.7.0_13 unix. JAVA_HOME , null. , java /, .

+2

JAVA_HOME System.getProperties() JRE, JDK. JDK :

Map<String, String> env = System.getenv();
 for (String envName : env.keySet())
 {
 System.out.format("%s=%s%n",
 envName,
 env.get(envName));
 }
+1

System.getProperty( "java.home" ) ?

"jre", , jre, , , JDK.

0

JAVA_HOME System.getProperties() JRE, JDK. JDK :

Map<String, String> env = System.getenv();
        for (String envName : env.keySet())
        {
            System.out.format("%s=%s%n",
                    envName,
                    env.get(envName));
        }
0

: , jdk, jdk. , .

, jdk. jre jdk .

, System.getProperty( "java.home" ), .

, .

0
, . Windows.
import java.io.File;

public class Main {
    public static void main(String[] args) {
        String JDK_VERSION = "jdk" + System.getProperty("java.version"); // finds the JDK version currently installed
        String PATH_VARIABLE = System.getenv("PATH"); // finds all the system environment variables

        // separates all the system variables
        String[] SYSTEM_VARIABLES = PATH_VARIABLE.split(";");

        // this object helps build a string
        StringBuilder builder = new StringBuilder();

        // loop through all the system environment variables
        for (String item : SYSTEM_VARIABLES) {
            // if the system variable contains the JDK version get it! (all lower case just to be safe)
            if (item.toLowerCase().contains(JDK_VERSION.toLowerCase())) {
                // adds the JDK path to the string builder
                builder.append(item);
            }
        }

        // stores the JDK path to a variable
        String result = builder.toString();
        // turns the path, which was a string in to a usable file object.
        File JDK_PATH = new File(result);
        // since the path is actually in the JDK BIN folder we got to go back 1 directory
        File JDK_PATH_FINAL = new File(JDK_PATH.getParent());
        // prints out the result
        System.out.println(JDK_PATH_FINAL);
    }
}

, java ( JDK). bin JDK, JDK String File JDK.

0

getenv java PATH.

0

, JDK, .

-, :

  • JAVA_HOME :

Windows ( );

C:\Program Files\Java\jdk1.6.0_41
//or
C:\Program Files(x86)\Java\jdk1.6.0_41

Linux ( ),

/usr/java/jdk1.6.0_41
//or
/usr/jvm/jdk1.6.0_41
//or
/opt/java/jdk1.6.0_41
  • JAVA_HOME:

Windows:

You have to change JAVA_HOME variable as manually

Linux:

You can use "update-java" script by WebUpd8 ([https://code.google.com/p/webupd8/downloads/list][1])
0

, ( Java_home .. JVM, script Java.

Java, API, .

, , .

, java.home java-, , .

Unix/Linux

. , ,

0

, :

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(/* your arguments here */);

.

0

, , System.getProperty("sun.boot.class.path"), System.getProperty("path.separator") JAR JDK.

, ( ):

sun.boot.class.path = "/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/jsse.jar:/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/laf.jar: "

path.separator = ":"

, JAR /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/.

, , OS X, Java. OS X, , ( ).

If you also want to support OS X, you may need to use the system property os.nameand write additional hoc code.

0
source

Just curious ... if you want to compile different Java code at runtime, why not use the Java Compiler API? If you do not call the java compiler using Runtime exec ()

0
source

All Articles