从命令行运行 jar 文件时设置目录路径
我有一个 jar 文件,其中有检测其绝对路径(启动该文件的当前目录)的函数。效果很好。
但现在,为了获得管理员权限,我从另一个 jar 文件启动此文件,同时使用 elevation 二进制可执行文件 类似:
Elevate.exe javaw.exe -jar path-to-my-jar-file
这里,请注意 Elevate.exe
和 jar 文件位于同一目录中,但是我尝试将两者都提供只是罐子文件名和绝对路径,但在这两种方式中,文件都会启动,它具有管理员权限,并且一切正常,除了现在相同的方法给出了错误的当前目录路径。
这次我得到: C:\Windows\System32
我已经尝试了很多东西,但是每次当我使用 Runtime.getRuntime().exec 从另一个 jar 文件使用上述方法启动这个 jar 时("cmd \\c ");
未正确检测当前目录路径。为什么会这样,在这种情况下我怎样才能找到正确的路径?
编辑: 我尝试使用以下方法获取正确的目录名称:
String dir = System.getProperty("user.dir") &&
String dir = new File (".").getAbsolutePath().toString();
独立启动文件时两者都返回相同的正确路径,从外部进程启动时返回 C:\Windows\System32 。请建议我应该做什么来解决这个问题。
I have a jar file, in which I have function which detects its absolute path (current directory from where this file is launched). It works fine.
But now, in order to get admin rights, I launch this file from another jar file, while using elevation binary executable something like:
Elevate.exe javaw.exe -jar path-to-my-jar-file
Here, please note that Elevate.exe
and jar file are in the same directory, however I tried giving both just the jar file name as well as absolute path, but in both ways, the file launches, it has admin rights and everything works fine except the fact that, now the same method gives a wrong current directory path.
This time I get: C:\Windows\System32
I have tried many things, but every time when I launch this jar using above method from another jar file using Runtime.getRuntime().exec("cmd \\c ");
the current directory path is not detected correctly. Why is that so, and how can I find out correct path in such a case?
EDIT:
I tried getting a correct directory name using:
String dir = System.getProperty("user.dir") &&
String dir = new File (".").getAbsolutePath().toString();
Both return the same correct path when file is launched independently, and C:\Windows\System32
when launched from external process. Please suggest what should I do to solve this problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们看一下Runtime类的exec方法:
然后是 exec(command, null, null) 的描述:
因此调用 exec(command) 会导致调用 exec(cmdarray, envp, dir) ),下面是 exec(cmdarray, envp, dir) 的部分描述:
在代码中,参数 dir 为 null,因此子进程继承了当前进程的当前工作目录,在本例中为 Evalute.exe 的工作目录
。
如果无论 jar 文件如何执行,您都想获得相同的结果,则必须显式指定工作目录,只需使用下面的代码:
而不是:
Let's have a look the exec method of class Runtime:
and then the description of exec(command, null, null):
so a invocation of exec(command) results in a invocation of exec(cmdarray, envp, dir), below is part of the description of exec(cmdarray, envp, dir):
In your code the parameter dir is null, so the subprocess inherits the current working directory of the current process, in this case, is working directory of Evalute.exe
.
if your want to get the same result regardingless of how the jar file is executed, you must specify the working directory explicitly, just use the code below:
instead of: