1359

I want to access my current working directory using Java.

My code:

 String currentPath = new java.io.File(".").getCanonicalPath();
 System.out.println("Current dir:" + currentPath);

 String currentDir = System.getProperty("user.dir");
 System.out.println("Current dir using System:" + currentDir);

Output:

Current dir: C:\WINDOWS\system32
Current dir using System: C:\WINDOWS\system32

My output is not correct because the C drive is not my current directory.

How to get the current directory?

auspicious99
  • 3,902
  • 1
  • 44
  • 58
Qazi
  • 13,791
  • 3
  • 15
  • 19
  • 3
    What is it you're trying to accomplish by accessing the working directory? Could it be done by using the class path instead? For example, if you need to read a text file on the file system, you can find it easily when it is on the class path. – earldouglas Feb 02 '11 at 05:53
  • 1
    how? Could you elaborate please? – C graphics Oct 31 '12 at 23:09
  • 1
    For some information about accessing a file on the class path, see http://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java – downeyt Jan 17 '16 at 12:47
  • 20
    For debugging purposes, the working directory could be useful to know if the program doesn't seem to be able to access files that exist. – nsandersen Mar 17 '16 at 13:49
  • 3
    Both methods (and the methods below) look correct. If you get the system directory as CWD then this might be due to a wrapper doing a CD before starting Java. For example javapath might do this. Specify the path to java.exe to the actual Java_:home directory directly to avoid this. – eckes Nov 20 '16 at 17:14
  • 3
    Bear in mind that one thing is the working directory, and other the directory whether your class resides. They usually aren't the same. – Fran Marzoa Mar 24 '18 at 15:22
  • @Qazi Did any of the below answers solve your case? Can you pick one of those as your answer? – Socrates Jul 18 '18 at 09:47
  • Knowledge of the current working directory is important for all relative paths. If you think that is irrelevant make sure you always access files via some absolute path. The classpath need not be the filesystem - it is entirely different. – Queeg May 27 '22 at 22:06

27 Answers27

1482

Code :

public class JavaApplication {
  public static void main(String[] args) {
    System.out.println("Working Directory = " + System.getProperty("user.dir"));
  }
}

This will print the absolute path of the current directory from where your application was initialized.


Explanation:

From the documentation:

java.io package resolve relative pathnames using current user directory. The current directory is represented as system property, that is, user.dir and is the directory from where the JVM was invoked.

Anish B.
  • 9,111
  • 3
  • 21
  • 41
Anuj Patel
  • 17,261
  • 3
  • 30
  • 57
  • 29
    @ubuntudroid: that's why i mentioned specifically that it will print the path from where the application had initialized. My guess the thread starter directly run the jar/program after starting commnad prompt (which is basically at C:\WINDOWS\system32). I hope you understand my point. Assuming you downvoted, appreciate that at least you cared to leave a response. :) – Anuj Patel Oct 29 '12 at 14:20
  • 2
    user.dir will get the path to the folder wherein the process was launched. To get the actual path to the application's main folder see my answer below. – Peter De Winter May 15 '13 at 14:31
  • The problem with the "user.dir" property is, as soon someone pass it as `-Duser.dir=...` or set it inside the code with `System.setProperty("user.dir", ...)` all code relying on it fails. – SubOptimal Dec 30 '14 at 12:43
  • 1
    I mean "all code relying on it **to find the current directory** fails.". Not all code in general. (I was to slow to edit the original comment) – SubOptimal Dec 30 '14 at 12:55
  • 13
    @SubOptimal if user setted -Duser.dir, propable he want to run this in custom working directory. – barwnikk Apr 18 '15 at 18:58
  • @barwnikk I full agree with you. In that case the user should not expect to get the directory from which `java` was called (must not the one where the `java` executable is sotred) by `System.getProperty("user.dir")`. What I meant all code which relies on that fact might not behave as expected. – SubOptimal Apr 20 '15 at 13:49
  • 8
    @indyaah infact this answer is wrong, there is a subtle difference between a user-working-directory and a current-working-directory of a system process (cwd); most of time the "user.dir" points to the cwd of a (java)process; but "user.dir" has different semantics and shall not be used to obtain the cwd of a java process; btw:there are more properties available to java process https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html just for reference – comeGetSome May 30 '15 at 10:10
  • I got `null` when using `System.out.println(System.getProperty("user.dir"))` – LittleLittleQ May 10 '17 at 09:22
  • 1
    Downvote for not explaining enough how System.getProperty("user.dir") works. – Philip Rego Oct 23 '17 at 19:37
  • try running this command with root user, you would find user.dir as "/" – Manish Bansal Jul 18 '18 at 13:19
  • This is more of a comment to the original question than an answer because the OP has already tried this option. – jacobcs Sep 09 '20 at 02:11
  • Great answer so far !! Works for any os.. :) – Anish B. Oct 26 '20 at 05:16
  • @indyaah what is this "subtle difference" between the user's working directory and current working directory? – xpusostomos Jun 29 '23 at 15:32
534

See: Path Operations (The Java™ Tutorials > Essential Classes > Basic I/O).

Using java.nio.file.Path and java.nio.file.Paths, you can do the following to show what Java thinks is your current path. This for 7 and on, and uses NIO.

Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current absolute path is: " + s);

This outputs:

Current absolute path is: /Users/george/NetBeansProjects/Tutorials

that in my case is where I ran the class from.

Constructing paths in a relative way, by not using a leading separator to indicate you are constructing an absolute path, will use this relative path as the starting point.

geoO
  • 5,502
  • 1
  • 13
  • 9
  • 3
    The first one haven' t checked, but the second one will actually get your home folder. Not the current working directory in which the application is running. – Peter De Winter May 15 '13 at 14:22
  • 20
    Please don't confuse the user's home directory ("user.home", /Users/george in your case) and the current working directory ("user.dir", which will be the directory from which you started the JVM for your application, so could be something like e.g. /Users/george/workspace/FooBarProject). – David Sep 20 '13 at 10:19
  • 3
    I prefer this way. When I need the parent of the working directory, this does *not* work: `Paths.get("").getParent()`, it gives `null`. Instead this works: `Paths.get("").toAbsolutePath().getParent()`. – Ole V.V. Oct 16 '16 at 08:47
  • If you need to get the parent of the current directory just use the "..". example: Paths.get("..").toAbsolutePath().normalize(); – A.Casanova Feb 08 '22 at 10:57
  • I've encountered (at least on Java 7) cases where `Paths.get("").toAbsolutePath()` was not returning the same value as `System.getProperty("user.dir")`. Thus they are not equivalent. The scenario was debugging tests run using Maven without forking (`forkCount=0`): using `Paths.get("")` was returning the root Maven module path (the directory in which the `mvn`command was started), while the `System.getProperty("user.dir")` returned the current Maven module path. Quite unexpected and probably related to not forking. – Jidehem Dec 04 '22 at 10:30
261

The following works on Java 7 and up (see here for documentation).

import java.nio.file.Paths;

Paths.get(".").toAbsolutePath().normalize().toString();
jasonmp85
  • 6,749
  • 2
  • 25
  • 41
Dmitry Bespalov
  • 5,179
  • 3
  • 26
  • 33
  • 11
    How is this better than the more portable `import java.io.File; File(".").getAbsolutePath()` ? – Evgeni Sergeev Jun 01 '16 at 15:20
  • 9
    When you say portable, you mean it works in Java 6 and earlier? `Paths.get()` may be considered better in that it gives direct access to the more powerful `Path` interface. – Ole V.V. Oct 16 '16 at 08:56
  • 11
    What is the potential advantage of using `.normalize()` in this context? – Ole V.V. Oct 16 '16 at 08:58
  • 9
    @OleV.V. From Javadoc: (*normalize method*) `Returns a path that is this path with redundant name elements eliminated.` – Stephan May 21 '17 at 17:46
  • What's the significance of `.` (dot)? does it matter if we omit the dot? – YaMiN Feb 03 '22 at 03:57
  • 1
    The dot represents the current directory. `./test` is the file `test` in the current directory on *nix operating systems. On Windows it is `.\test`. – Björn Zurmaar May 06 '22 at 10:41
82

This will give you the path of your current working directory:

Path path = FileSystems.getDefault().getPath(".");

And this will give you the path to a file called "Foo.txt" in the working directory:

Path path = FileSystems.getDefault().getPath("Foo.txt");

Edit : To obtain an absolute path of current directory:

Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();

* Update * To get current working directory:

Path path = FileSystems.getDefault().getPath("").toAbsolutePath();
Mark
  • 2,260
  • 18
  • 27
  • 14
    this just returns '.' for me. – john k Feb 01 '18 at 00:53
  • 3
    Yes, in many systems that will be the reference to the working directory. To get the absolute path you can add one more method call `Path path = FileSystems.getDefault().getPath(".").toAbsolutePath();` – Mark Feb 01 '18 at 19:49
  • 2
    You don't need the foo.txt, just put in an empty string to get the directory – john k Mar 05 '18 at 02:41
  • 1
    On Windows (10) this just gives me a `Path` object pointing to a file called `.` inside the current working dir. Using an empty string, rather than `"."` worked for me. – Kröw Apr 18 '19 at 06:32
81

Java 11 and newer

This solution is better than others and more portable:

Path cwd = Path.of("").toAbsolutePath();

Or even

String cwd = Path.of("").toAbsolutePath().toString();
freedev
  • 25,946
  • 8
  • 108
  • 125
  • This is exactly the same as the answer from comeGetSome and is actually the Java <7 way – GoGoris Jan 03 '20 at 14:59
  • 2
    it should be Path cwd = Paths.get("").toAbsolutePath(); – Jahangir Alam Jun 19 '20 at 10:25
  • 8
    Better to use `Path.of`, because [Paths might get deprecated](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/nio/file/Paths.html). Also, `Paths.get` just calls `Path.of`. – the Hutt Mar 29 '21 at 02:12
  • @onkarruikar good point, I’ll update the answer – freedev Mar 29 '21 at 05:57
  • Also prefer the dot rather than empty string as it is more understood in windows or posix system, it's the current directory. (Suggested in [Volodya Lombrozo's answer](https://stackoverflow.com/a/66786617/48136)). – bric3 Jun 21 '23 at 08:38
38

This is the solution for me

File currentDir = new File("");
user2430452
  • 397
  • 3
  • 3
  • 2
    This has side effects when you use such a File object as a parent of another File: new File(new File(""), "subdir") will not work as expected – MRalwasser Oct 17 '14 at 14:22
  • 17
    To fix this, use `new File("").getAbsoluteFile()` instead. – MRalwasser Oct 17 '14 at 14:34
  • 5
    For what it's worth, I had better luck with File("."). – keshlam Dec 02 '14 at 15:51
  • [How To Define a Relative Path in Java](http://stackoverflow.com/questions/14209085/how-to-define-a-relative-path-in-java) This Page helped me. Also I assumed that I should use `/` when creating a relative path. I was wrong, don't start with `/`. `../` also works for going up in the directory tree. – Irrationalkilla Feb 05 '16 at 01:05
  • @keshlam That gave me a file in the current directory called `.`. – Kröw Jun 02 '19 at 02:12
30

What makes you think that c:\windows\system32 is not your current directory? The user.dir property is explicitly to be "User's current working directory".

To put it another way, unless you start Java from the command line, c:\windows\system32 probably is your CWD. That is, if you are double-clicking to start your program, the CWD is unlikely to be the directory that you are double clicking from.

Edit: It appears that this is only true for old windows and/or Java versions.

Paul Wagland
  • 27,756
  • 10
  • 52
  • 74
  • 3
    This doesn't seem to be true, at least not on my Windows 7 machine using Java 7. `user.dir` is consistently the folder where I double-clicked the jar file. – Jolta Feb 25 '15 at 09:40
26

Use CodeSource#getLocation().

This works fine in JAR files as well. You can obtain CodeSource by ProtectionDomain#getCodeSource() and the ProtectionDomain in turn can be obtained by Class#getProtectionDomain().

public class Test {
    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
    }
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
Amin Bahiraee
  • 538
  • 10
  • 20
24
this.getClass().getClassLoader().getResource("").getPath()
Spudley
  • 166,037
  • 39
  • 233
  • 307
Peter De Winter
  • 1,183
  • 2
  • 15
  • 27
  • 13
    Throws a NPE when I launch my application from a JAR file by double-clicking it. – Matthew Wise Aug 02 '13 at 16:34
  • 2
    This returns `""` if the application is running from a JAR file, or a CLASSPATH element. Not what was asked for. – user207421 Oct 01 '17 at 02:13
  • @Zizouz212 `getClass()` is an object method, so in a static context just removing the `this` doesn't work. You'd have to explicitly refer to the class you're in by doing `MyClass.class.getClassLoader().....`. – Kröw Jun 02 '19 at 02:14
19

generally, as a File object:

File getCwd() {
  return new File("").getAbsoluteFile();
}

you may want to have full qualified string like "D:/a/b/c" doing:

getCwd().getAbsolutePath()
comeGetSome
  • 1,913
  • 19
  • 20
15

I'm on Linux and get same result for both of these approaches:

@Test
public void aaa()
{
    System.err.println(Paths.get("").toAbsolutePath().toString());

    System.err.println(System.getProperty("user.dir"));
}

Paths.get("") docs

System.getProperty("user.dir") docs

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
Bohdan
  • 16,531
  • 16
  • 74
  • 68
7

I hope you want to access the current directory including the package i.e. If your Java program is in c:\myApp\com\foo\src\service\MyTest.java and you want to print until c:\myApp\com\foo\src\service then you can try the following code:

String myCurrentDir = System.getProperty("user.dir")
            + File.separator
            + System.getProperty("sun.java.command")
                    .substring(0, System.getProperty("sun.java.command").lastIndexOf("."))
                    .replace(".", File.separator);
    System.out.println(myCurrentDir);

Note: This code is only tested in Windows with Oracle JRE.

JSS
  • 2,061
  • 1
  • 20
  • 26
  • 7
    It would be disservice not to downvote this answer. Please think more carefully before posting. Your code is broken, unless all these are true: 1. the JRE is Oracle's, otherwise there will be no "sun.java.command" system property → NPE; 2. the OS is Windows (Use `File.separator` instead, or a multi-argument `File` constructor); 3. the classpath is specificed on the command line, _and_ the 'current directory including the package'(??) is: a. specified first, b. specified absolutely, c. matches the CWD exactly (even with Windows' case insensitivity), and d. is a descendent of the CWD – Michael Scheper May 15 '13 at 02:43
  • That addresses points 1 and 2. But unless I'm missing something, you're still relying on the classpath being specified in the command line (i.e. not in an environment variable), and for the 'current directory including the package' (I admit I don't really understand what you mean by that) being a descendent of specifically the first element in the classpath. And the case matching problem remains. I'm sorry if my comment wasn't helpful; I sacrificed clarity to keep within the comment character limit. – Michael Scheper Jun 06 '13 at 04:17
  • @Inversus, it only "works perfectly" in some environments; you just happened to be lucky enough to test it in onesuch. Writing software that fails in legitimate runtime environments is not good practice, even when your set of test environments isn't expansive enough to include them. – Charles Duffy Apr 10 '14 at 02:07
  • @CharlesDuffy You're right, that is not good practice. Fortunately, this solution "solv[ing] my specific issue" did not cause it to "[fail] in legitimate runtime environments." In fact, it helped me solve such a failure and write more robust code, besides solving the very specific issue I had (which was only somewhat related to this question/answer). I guess I was just lucky to find it. – Inversus Apr 24 '14 at 23:32
5

On Linux when you run a jar file from terminal, these both will return the same String: "/home/CurrentUser", no matter, where youre jar file is. It depends just on what current directory are you using with your terminal, when you start the jar file.

Paths.get("").toAbsolutePath().toString();

System.getProperty("user.dir");

If your Class with main would be called MainClass, then try:

MainClass.class.getProtectionDomain().getCodeSource().getLocation().getFile();

This will return a String with absolute path of the jar file.

Jan Povolný
  • 59
  • 1
  • 1
5

Using Windows user.dir returns the directory as expected, but NOT when you start your application with elevated rights (run as admin), in that case you get C:\WINDOWS\system32

SijeDeHaan
  • 175
  • 2
  • 2
4

Mention that it is checked only in Windows but i think it works perfect on other Operating Systems [Linux,MacOs,Solaris] :).


I had 2 .jar files in the same directory . I wanted from the one .jar file to start the other .jar file which is in the same directory.

The problem is that when you start it from the cmd the current directory is system32.


Warnings!

  • The below seems to work pretty well in all the test i have done even with folder name ;][[;'57f2g34g87-8+9-09!2#@!$%^^&() or ()%&$%^@# it works well.
  • I am using the ProcessBuilder with the below as following:

..

//The class from which i called this was the class `Main`
String path = getBasePathForClass(Main.class);
String applicationPath=  new File(path + "application.jar").getAbsolutePath();


System.out.println("Directory Path is : "+applicationPath);

//Your know try catch here
//Mention that sometimes it doesn't work for example with folder `;][[;'57f2g34g87-8+9-09!2#@!$%^^&()` 
ProcessBuilder builder = new ProcessBuilder("java", "-jar", applicationPath);
builder.redirectErrorStream(true);
Process process = builder.start();

//...code

getBasePathForClass(Class<?> classs):

    /**
     * Returns the absolute path of the current directory in which the given
     * class
     * file is.
     * 
     * @param classs
     * @return The absolute path of the current directory in which the class
     *         file is.
     * @author GOXR3PLUS[StackOverFlow user] + bachden [StackOverFlow user]
     */
    public static final String getBasePathForClass(Class<?> classs) {

        // Local variables
        File file;
        String basePath = "";
        boolean failed = false;

        // Let's give a first try
        try {
            file = new File(classs.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

            if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
                basePath = file.getParent();
            } else {
                basePath = file.getPath();
            }
        } catch (URISyntaxException ex) {
            failed = true;
            Logger.getLogger(classs.getName()).log(Level.WARNING,
                    "Cannot firgue out base path for class with way (1): ", ex);
        }

        // The above failed?
        if (failed) {
            try {
                file = new File(classs.getClassLoader().getResource("").toURI().getPath());
                basePath = file.getAbsolutePath();

                // the below is for testing purposes...
                // starts with File.separator?
                // String l = local.replaceFirst("[" + File.separator +
                // "/\\\\]", "")
            } catch (URISyntaxException ex) {
                Logger.getLogger(classs.getName()).log(Level.WARNING,
                        "Cannot firgue out base path for class with way (2): ", ex);
            }
        }

        // fix to run inside eclipse
        if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
                || basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
            basePath = basePath.substring(0, basePath.length() - 4);
        }
        // fix to run inside netbeans
        if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
            basePath = basePath.substring(0, basePath.length() - 14);
        }
        // end fix
        if (!basePath.endsWith(File.separator)) {
            basePath = basePath + File.separator;
        }
        return basePath;
    }
GOXR3PLUS
  • 6,877
  • 9
  • 44
  • 93
2

assume that you're trying to run your project inside eclipse, or netbean or stand alone from command line. I have write a method to fix it

public static final String getBasePathForClass(Class<?> clazz) {
    File file;
    try {
        String basePath = null;
        file = new File(clazz.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        if (file.isFile() || file.getPath().endsWith(".jar") || file.getPath().endsWith(".zip")) {
            basePath = file.getParent();
        } else {
            basePath = file.getPath();
        }
        // fix to run inside eclipse
        if (basePath.endsWith(File.separator + "lib") || basePath.endsWith(File.separator + "bin")
                || basePath.endsWith("bin" + File.separator) || basePath.endsWith("lib" + File.separator)) {
            basePath = basePath.substring(0, basePath.length() - 4);
        }
        // fix to run inside netbean
        if (basePath.endsWith(File.separator + "build" + File.separator + "classes")) {
            basePath = basePath.substring(0, basePath.length() - 14);
        }
        // end fix
        if (!basePath.endsWith(File.separator)) {
            basePath = basePath + File.separator;
        }
        return basePath;
    } catch (URISyntaxException e) {
        throw new RuntimeException("Cannot firgue out base path for class: " + clazz.getName());
    }
}

To use, everywhere you want to get base path to read file, you can pass your anchor class to above method, result may be the thing you need :D

Best,

bachden
  • 441
  • 3
  • 9
  • 2
    This returns the location of the JAR file. Not what was asked for. – user207421 Oct 01 '17 at 02:14
  • 1
    @user207421 yes I know this answer is not the true answer for the question, but most of time, everybody want to get the "directory where the jars located" instead of "command line working directory". – bachden Mar 31 '19 at 10:23
2

For Java 11 you could also use:

var path = Path.of(".").toRealPath();
Volodya Lombrozo
  • 2,325
  • 2
  • 16
  • 34
1

This is a very confuse topic, and we need to understand some concepts before providing a real solution.

  1. The File, and NIO File Api approaches with relative paths "" or "." uses internally the system parameter "user.dir" value to determine the return location.

  2. The "user.dir" value is based on the USER working directory, and the behavior of that value depends on the operative system, and the way the jar is executed.

  3. For example, executing a JAR from Linux using a File Explorer (opening it by double click) will set user.dir with the user home directory, regardless of the location of the jar. If the same jar is executed from command line, it will return the jar location, because each cd command to the jar location modified the working directory.

Having said that, the solutions using Java NIO, Files or "user.dir" property will work for all the scenarios in the way the "user.dir" has the correct value.

String userDirectory = System.getProperty("user.dir");
String userDirectory2 = new File("").getAbsolutePath();
String userDirectory3 = Paths.get("").toAbsolutePath().toString();

We could use the following code:

new File(MyApp.class.getProtectionDomain()
                     .getCodeSource()
                     .getLocation()
                     .toURI().getPath())
     .getParent();

to get the current location of the executed JAR, and personally I used the following approach to get the expected location and overriding the "user.dir" system property at the very beginning of the application. So, later when the other approaches are used, I will get the expected values always.

More details here -> https://blog.adamgamboa.dev/getting-current-directory-path-in-java/

    public class MyApp {
      
      static {
        //This static block runs at the very begin of the APP, even before the main method.
        try{
          File file = new File(MyApp.class.getProtectionDomain().getCodeSource()
                           .getLocation().toURI().getPath());
          String basePath = file.getParent();
          //Overrides the existing value of "user.dir"
          System.getProperties().put("user.dir", basePath);
        }catch(URISyntaxException ex){
          //log the error
        }
      }
     
      public static void main(String args []){
        //Your app logic
        
        //All these approaches should return the expected value
        //regardless of the way the jar is executed.
        String userDirectory = System.getProperty("user.dir");
        String userDirectory2 = new File("").getAbsolutePath();
        String userDirectory3 = Paths.get("").toAbsolutePath().toString();
      }
    }

I hope this explanation and details are helpful to others...

0

Current working directory is defined differently in different Java implementations. For certain version prior to Java 7 there was no consistent way to get the working directory. You could work around this by launching Java file with -D and defining a variable to hold the info

Something like

java -D com.mycompany.workingDir="%0"

That's not quite right, but you get the idea. Then System.getProperty("com.mycompany.workingDir")...

L Joey
  • 155
  • 2
  • 8
MJB
  • 9,352
  • 6
  • 34
  • 49
  • 9
    Not relevant to the question. – Peter De Winter May 15 '13 at 14:28
  • 1
    It does have a meaning to Java - it's the location on disk where files that you open with relative pathnames are relative to. – Rob I Jul 29 '13 at 16:36
  • 2
    Yes, it has a meaning. My words were somewhat poorly chosen. But you miss the point - prior to Java 7 there was no way to know the current working directory, and different implementations set them...differently... – MJB Jun 25 '14 at 03:59
0

This is my silver bullet when ever the moment of confusion bubbles in.(Call it as first thing in main). Maybe for example JVM is slipped to be different version by IDE. This static function searches current process PID and opens VisualVM on that pid. Confusion stops right there because you want it all and you get it...

  public static void callJVisualVM() {
    System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
    //next search current jdk/jre
    String jre_root = null;
    String start = "vir";
    try {
        java.lang.management.RuntimeMXBean runtime =
                java.lang.management.ManagementFactory.getRuntimeMXBean();
        String jvmName = runtime.getName();
        System.out.println("JVM Name = " + jvmName);
        long pid = Long.valueOf(jvmName.split("@")[0]);
        System.out.println("JVM PID  = " + pid);
        Runtime thisRun = Runtime.getRuntime();
        jre_root = System.getProperty("java.home");
        System.out.println("jre_root:" + jre_root);
        start = jre_root.concat("\\..\\bin\\jvisualvm.exe " + "--openpid " + pid);
        thisRun.exec(start);
    } catch (Exception e) {
        System.getProperties().list(System.out);
        e.printStackTrace();
    }
}
Tonecops
  • 127
  • 9
0

This isn't exactly what's asked, but here's an important note: When running Java on a Windows machine, the Oracle installer puts a "java.exe" into C:\Windows\system32, and this is what acts as the launcher for the Java application (UNLESS there's a java.exe earlier in the PATH, and the Java app is run from the command-line). This is why File(".") keeps returning C:\Windows\system32, and why running examples from macOS or *nix implementations keep coming back with different results from Windows.

Unfortunately, there's really no universally correct answer to this one, as far as I have found in twenty years of Java coding unless you want to create your own native launcher executable using JNI Invocation, and get the current working directory from the native launcher code when it's launched. Everything else is going to have at least some nuance that could break under certain situations.

Ted
  • 48
  • 5
  • This was true long ago (when this Q was posted), but Microsoft discouraged apps changing system32, and since at least 2015 the Oracle Windows installers put their stub in either `\programdata\Oracle\Java\javapath` or `\Program Files [(x86)]\Common Files\Oracle\Java\javapath`as approved by MS – dave_thompson_085 Sep 16 '20 at 07:17
  • Noticed that myself recently--good update! I think older installers (Java 1.8) will still do the original behavior, but definitely the behavior you cite is one I'm seeing from the more recent builds/installs. (Personally I dislike a global Java anywhere, but that's me.) – Ted May 14 '22 at 22:42
0

Try something like this I know I am late for the answer but this obvious thing happened in java8 a new version from where this question is asked but..

The code

import java.io.File;

public class Find_this_dir {

    public static void main(String[] args) {

//some sort of a bug in java path is correct but file dose not exist
        File this_dir = new File("");

//but these both commands work too to get current dir        
//      File this_dir_2 = new File(this_dir.getAbsolutePath());
        File this_dir_2 = new File(new File("").getAbsolutePath());

        System.out.println("new File(" + "\"\"" + ")");
        System.out.println(this_dir.getAbsolutePath());
        System.out.println(this_dir.exists());
        System.out.println("");
        System.out.println("new File(" + "new File(" + "\"\"" + ").getAbsolutePath()" + ")");
        System.out.println(this_dir_2.getAbsolutePath());
        System.out.println(this_dir_2.exists());
    }
}

This will work and show you the current path but I don't now why java fails to find current dir in new File(""); besides I am using Java8 compiler...

This works just fine I even tested it new File(new File("").getAbsolutePath());

Now you have current directory in a File object so (Example file object is f then),

f.getAbsolutePath() will give you the path in a String varaible type...

Tested in another directory that is not drive C works fine

Avon97
  • 47
  • 12
0

My favorite method is to get it from the system environment variables attached to the current running process. In this case, your application is being managed by the JVM.

String currentDir = System.getenv("PWD");
/*
 /home/$User/Documents/java
*/

To view other environment variables that you might find useful like, home dir, os version ........

//Home directory
String HomeDir = System.getEnv("HOME");


//Outputs for unix
/home/$USER

//Device user
String user = System.getEnv("USERNAME");


//Outputs for unix
$USER

The beautiful thing with this approach is that all paths will be resolved for all types of OS platform

Mainz007
  • 533
  • 5
  • 16
Andrew Mititi
  • 933
  • 12
  • 11
0

You might use new File("./"). This way isDirectory() returns true (at least on Windows platform). On the other hand new File("") isDirectory() returns false.

Wortig
  • 963
  • 2
  • 11
  • 37
0

Not exactly sure what you're trying to accomplish but the above answers work on the current working directory where you are asking from not from where the program is actually located.

For instance:

$> mkdir -p /tmp/paths/check 
$> cat > /tmp/paths/check/GetPath.java
import java.nio.file.Paths;
import java.nio.file.FileSystems;

public class GetPath {
// Note: these methods work slightly differently, the last two will provide the working dir
// for where this program was launched, while the first will get the cwd from where this
// program resides.
public static void main(String[] args) {
        String rootPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println("Thread rootPath is "+rootPath);
        System.out.println("System property user.dir is "+System.getProperty("user.dir"));
        System.out.println("NIO Paths way is "+Paths.get("").toAbsolutePath());
        System.out.println("NIO FileSystems way is "+FileSystems.getDefault().getPath("").toAbsolutePath());
}
}

Then if you run it from /tmp, you will see:

$> cd /tmp/paths/check; javac GetPath.java
$> cd /tmp
$> java -cp paths/check GetPath
Thread rootPath is /tmp/paths/check/
system property user.dir is /tmp
NIO Paths way is/tmp
NIO FileSystems way is/tmp

So the first method using the ContextClassLoader may be more appropriate depending on what you are trying to accomplish.

Adam D.
  • 159
  • 1
  • 5
-1

None of the answers posted here worked for me. Here is what did work:

java.nio.file.Paths.get(
  getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
);

Edit: The final version in my code:

URL myURL = getClass().getProtectionDomain().getCodeSource().getLocation();
java.net.URI myURI = null;
try {
    myURI = myURL.toURI();
} catch (URISyntaxException e1) 
{}
return java.nio.file.Paths.get(myURI).toFile().toString()
VenerableAgents
  • 645
  • 1
  • 8
  • 16
-6

System.getProperty("java.class.path")

Marko Stojkovic
  • 3,255
  • 4
  • 19
  • 20