简体   繁体   English

在Java中获取当前用户的路径而不是应用程序路径

[英]Getting the current user's path rather than application path in java

I am trying to get the current users path in a giant command line application that has multiple dependencies. 我试图在具有多个依赖项的巨型命令行应用程序中获取当前用户路径。 Every time a "." 每次一个“。” is used, it gives me the application path (where the jar exists), rather than the current user path(where the call is being made). 使用它,它为我提供了应用程序路径(jar所在的位置),而不是当前用户路径(正在进行调用的位置)。

So, when this is ran: 因此,当运行此命令时:

File file = new File(".");
System.out.println(file.getCanonicalPath());

Gives me the path that the application exists in. 给我应用程序所在的路径。

But when I create a separate small application, and use the same code. 但是当我创建一个单独的小型应用程序时,并使用相同的代码。 Call the jar from a different directory, it gives the current user path. 从其他目录调用jar,它会提供当前用户路径。

I am using JSAP command line parser for the command line arguments, its acting the same way. 我使用JSAP命令行解析器作为命令行参数,其作用方式相同。 How can this be solved? 如何解决呢? I want my big application to get the current user path, not application path. 我希望我的大型应用程序获得当前的用户路径,而不是应用程序路径。

What would cause them to behave differently? 是什么使他们的行为有所不同?

I think you'll find that the batch file (/shell script) which launches your "big application" is changing directory to the main jar file's directory before kicking off Java, which is why your simple test application returns the user's working directory for new File(".") while the big app returns the jar file's directory. 我认为您会发现启动“大应用程序”的批处理文件(/ shell脚本)在启动Java之前已将目录更改为主jar文件的目录,这就是为什么您的简单测试应用程序会返回用户new File(".")的工作目录的原因new File(".")而大型应用程序返回jar文件的目录。

Try storing the user's CWD early in the batch file and then passing it to Java: 尝试尽早将用户的CWD存储在批处理文件中,然后将其传递给Java:

set savedcwd=%cd%
... later on ...
java "-Dsavedcwd=%savedcwd%"

then in your application 然后在您的应用程序中

String savedcwd = System.getProperty("savedcwd");

http://www.mindspring.com/~mgrand/java-system-properties.htm http://www.mindspring.com/~mgrand/java-system-properties.htm

you want "user.home" property, like 您想要“ user.home”属性,例如

System.getProperty("user.home");
String currentDir = new File(".").getAbsolutePath();
OR
System.getProperty("user.dir")

1) As stated above, if you want to get "current directory", one way is to use File(".").getAbsolutePath() 1)如上所述,如果要获取“当前目录”,一种方法是使用File(".").getAbsolutePath()

2) If you want to get the user's $PATH variable (or any environment variable), use System.getenv() : 2)如果要获取用户的$ PATH变量(或任何环境变量),请使用System.getenv()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM