Path 在Java中查找JDK路径并将其存储为字符串
我想在多个操作系统上找到JDK路径 我不确定是否有一个很好的方法来做这件事,因为我一直在尝试,但失败了 对于Windows,它可能是这样的-Path 在Java中查找JDK路径并将其存储为字符串,path,java,Path,Java,我想在多个操作系统上找到JDK路径 我不确定是否有一个很好的方法来做这件事,因为我一直在尝试,但失败了 对于Windows,它可能是这样的-C:\ProgramFiles\Java\jdk1.7.0\u 07或这样 C:\ProgramFiles(x86)\Java\jdk1.7.0\u 07 对于Linux,应该是这样的-/usr/java/jdk1.7.0_07 我希望这适用于安装的任何JDK版本,因此Java\JDK后面的数字是不相关的 我将使用System.setProperty(“ja
C:\ProgramFiles\Java\jdk1.7.0\u 07
或这样
C:\ProgramFiles(x86)\Java\jdk1.7.0\u 07
对于Linux,应该是这样的-/usr/java/jdk1.7.0_07
我希望这适用于安装的任何JDK版本,因此Java\JDK后面的数字是不相关的
我将使用System.setProperty(“java.home”,path)代码>
基本上,我想做的是在运行程序时,将java.home设置为当前机器上安装的JDK,但是获取JDK路径非常困难,有什么解决方案吗?System.getProperty(“java.home”)对您来说不够好吗
如果它以“jre”结尾,您就会知道这就是jre,您可以尝试遍历并找到根文件夹,并检查只有JDK才能提供的不同文件。System.getProperties()中的JAVA_HOME变量指的是jre,而不是JDK。
您应该能够通过以下方式找到JDK:
Map<String, String> env = System.getenv();
for (String envName : env.keySet())
{
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
Map<String, String> env = System.getenv();
for (String envName : env.keySet())
{
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
Map env=System.getenv();
for(字符串envName:env.keySet())
{
System.out.format(“%s=%s%n”,
我的名字,
env.get(envName));
}
JAVA_HOME应该指向所有操作系统中的JDK安装路径,而JRE_HOME应该指向JRE安装路径
您可以选择安装jdk的位置,也可以安装多个jdk。所以我不认为这有一个标准变量
让我们假设标准目录结构已用于安装jdk。在此场景中,jre和jdk安装将位于同一目录下
因此,一旦您获得System.getProperty(“java.home”),然后简单地搜索目录
希望对您有所帮助。您可以通过查看javac的安装位置来找到JDK路径。
假设“javac”在系统的环境路径中,那么您可以通过将“where 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不在windows上的PATH环境变量中,因此无法使用该方法找到。这在Unix上不太可能,因为Unix通常会自动将jdk/bin目录添加到路径中。
此外,这将返回命令行中当前使用的javac版本,不一定是安装的最新版本。因此,如果安装了7u12和7u13,但命令提示符设置为使用7u12,则将返回该路径
仅在多台Windows计算机上测试,但在这些计算机上运行良好
希望这是有帮助的 天哪,这件事太复杂了,但我完成了。虽然它只在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路径的方法)。由于系统变量path实际上位于JDK bin文件夹中,它将JDK pathString
转换为一个文件
,并返回一个文件夹到JDK目录中。您可以使用java的getenv函数来获取路径。我认为这是您最好的选择(因为启动JVM不需要声明Java_home等,所以我可以在脚本中使用完整路径并启动Java
获取java进程id,使用API获取该进程的路径
这不是一个完整的解决方案,而是一条如何做到这一点的指导方针
如果您确信java.home在您的所有java应用程序中都设置正确,那么您可以按照其他答案中所述使用它
帮助获取进程id的路径
同样需要windows。我确信它就像在工具中看到的那样。如果您想在程序中编译程序,为什么不采取以下方法:
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(/* your arguments here */);
完整描述。我不知道有什么大不了的
public class Main implements Serializable{
public static void main(String[] args) {
System.out.println(System.getenv("JAVA_HOME"));
}
}
在windows上打印C:\Program Files\Java\jdk1.7.0
,在unix系统上打印/usr/Java/jdk1.7.0\u 13
。如果未设置environment属性Java\u HOME
,则返回null。您应该认为这意味着Java未正确安装/配置,因此应用程序无法正常运行。下注可能是查看System.getProperty(“sun.boot.class.path”)
的值,根据System.getProperty(“path.separator”)
的值标记它,并查找标准JDK JAR文件
例如,在我的系统上,我得到(为了可读性而截断):
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机器,你可以通过我们刚刚计算的值(我相信它是值的父目录)计算出安装目录
如果您还想支持OS X,则可能必须使用OS.name系统属性并编写add hoc代码。system.getProperties()中的JAVA_HOME变量指的是JRE而不是JDK。您应该能够通过以下方式找到JDK:
Map<String, String> env = System.getenv();
for (String envName : env.keySet())
{
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
Map<String, String> env = System.getenv();
for (String envName : env.keySet())
{
System.out.format("%s=%s%n",
envName,
env.get(envName));
}
Map env=System.getenv();
for(字符串envName:env.keySet())
{
System.out.format(“%s=%s%n”,
我的名字,
环境获取(env.get)