Reputation: 24596
I need to execute a java application using ProcessBuilder
. I also need to use the same java executable in the called process that is being used by the calling application.
Is there a platform independent way to retrieve the current java executable path and file name?
I've seen some code snippets similar to this:
public static boolean isWindows() {
return (System.getProperty("os.name").toLowerCase().indexOf("win") >= 0);
}
public static String getJavaExecutablePath() {
String executable = "java";
if (isWindows()) {
executable = executable + ".exe";
}
File path = new File(System.getProperty("java.home"), "/bin/" + executable);
return path.getAbsolutePath();
}
The above code will probably need to be improved to use File.separator
.
Is the above all that is required, or is there something else to consider, for example case sensitivity?
Ideally, there would be a library available for getting the OS path, but that is probably a question for a different forum.
Upvotes: 0
Views: 622
Reputation: 560
First, the most important thing for your requirement is System.getProperty("java.home"), you've got it already.
Secondly, don't worry about case sensitivity, the path '$JAVA_HOME/bin/java' always be in lower case in every java release, and there are already many other projects depend on this.
Last thing, you don't have to use a '/' or '\' to build the absolute path, consider this:
File path = new File(new File(System.getProperty("java.home"), "bin"), executable);
As you mentioned the File.separator did similar thing, but that is talking about a string, and File talks about file.
Here is a discussion about File path
Upvotes: 1