开发者

How to get the current working directory in Java?

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.getPrope开发者_运维问答rty("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?


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.


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.


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

import java.nio.file.Paths;

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


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


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


This is the solution for me

File currentDir = new File("");


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.


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


this.getClass().getClassLoader().getResource("").getPath()


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


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


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.


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.


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


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:

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜