从 java 代码中以编程方式查找绝对 java.exe 路径 [英] Find absolute java.exe path programmatically from java code

查看:13
本文介绍了从 java 代码中以编程方式查找绝对 java.exe 路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个由用户启动的 java jar 或类文件(假设 java 路径在环境变量中设置),那么我如何从代码中找出 java.exe/javaw.exe 的绝对路径从中启动此文件.

就像在 ubuntu 上一样,我们可以运行:% which java 并显示路径.

但是在 Windows 上,如果我检查 System.getenv() 可能会发现有多个路径,例如旧版本或新版本.如果通过 cmd 行,我运行 java -version 它不会显示路径.

你能告诉我通过纯 java 或 windows 上的命令行如何找到 javaw.exe 的位置吗?

解决方案

String javaHome = System.getProperty("java.home");

<小时><块引用>

您能否通过纯 Java 告诉我...在 windows 上如何找到 javaw.exe 的位置?

例如

import java.io.File;类 JavawLocation {公共静态无效主(字符串 [] args){String javaHome = System.getProperty("java.home");File f = new File(javaHome);f = new File(f, "bin");f = new File(f, "javaw.exe");System.out.println(f + " 存在:" + f.exists());}}

输出

C:Program Files (x86)Javajdk1.6.0_29jreinjavaw.exe 存在:true按任意键继续 ...

是的,我相信这会在 JRE 中工作.

If I have a java jar or class file which is launched by the user (assuming java path is set in environment variables), so how can i from within the code, figure out absolute path of java.exe/javaw.exe from which this file is being launched.

Like on ubuntu we can run: % which java and it shows the path.

However on windows, if i check System.getenv() it may happen that there are multiple path's found e.g for old or new version. If through cmd line, I run java -version it does not show the path.

Can you tell me either through pure java or command line on windows how is it possible to find out the location of javaw.exe?

解决方案

String javaHome = System.getProperty("java.home");


Can you tell me either through pure Java ... on windows how is it possible to find out the location of javaw.exe?

E.G.

import java.io.File;

class JavawLocation {

    public static void main(String[] args) {
        String javaHome = System.getProperty("java.home");
        File f = new File(javaHome);
        f = new File(f, "bin");
        f = new File(f, "javaw.exe");
        System.out.println(f + "    exists: " + f.exists());
    }
}

Output

C:Program Files (x86)Javajdk1.6.0_29jreinjavaw.exe    exists: true
Press any key to continue . . .

And yes, I am confident that will work in a JRE.

这篇关于从 java 代码中以编程方式查找绝对 java.exe 路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆