简体   繁体   中英

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).

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.

I am using JSAP command line parser for the command line arguments, its acting the same way. 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.

Try storing the user's CWD early in the batch file and then passing it to 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

you want "user.home" property, like

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()

2) If you want to get the user's $PATH variable (or any environment variable), use System.getenv() :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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