Как найти путь к папке java

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.'s user avatar

Anish B.

9,0073 gold badges19 silver badges41 bronze badges

answered Sep 29, 2011 at 21:12

Anuj Patel's user avatar

Anuj PatelAnuj Patel

17.1k3 gold badges29 silver badges57 bronze badges

12

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.

Mohammad Rifat Arefin's user avatar

answered Apr 11, 2013 at 17:10

geoO's user avatar

geoOgeoO

5,3921 gold badge13 silver badges9 bronze badges

5

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

import java.nio.file.Paths;

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

jasonmp85's user avatar

jasonmp85

6,7392 gold badges25 silver badges41 bronze badges

answered Mar 12, 2014 at 12:03

Dmitry Bespalov's user avatar

Dmitry BespalovDmitry Bespalov

5,1693 gold badges25 silver badges33 bronze badges

6

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

Loyal Service's user avatar

answered Sep 15, 2017 at 20:01

Mark's user avatar

MarkMark

2,20418 silver badges26 bronze badges

4

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

answered Jun 25, 2018 at 16:29

freedev's user avatar

freedevfreedev

25k8 gold badges108 silver badges124 bronze badges

4

This is the solution for me

File currentDir = new File("");

answered May 28, 2013 at 23:09

user2430452's user avatar

user2430452user2430452

3873 silver badges3 bronze badges

5

What makes you think that c:windowssystem32 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:windowssystem32 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.

answered Feb 2, 2011 at 5:39

Paul Wagland's user avatar

Paul WaglandPaul Wagland

27.4k10 gold badges52 silver badges74 bronze badges

1

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

Spudley's user avatar

Spudley

165k39 gold badges231 silver badges306 bronze badges

answered May 15, 2013 at 13:50

Peter De Winter's user avatar

Peter De WinterPeter De Winter

1,1732 gold badges15 silver badges27 bronze badges

3

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

answered Jan 26, 2015 at 12:13

comeGetSome's user avatar

comeGetSomecomeGetSome

1,92319 silver badges20 bronze badges

3

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's user avatar

answered Dec 28, 2013 at 3:11

Bohdan's user avatar

BohdanBohdan

16.4k15 gold badges73 silver badges68 bronze badges

I hope you want to access the current directory including the package i.e. If your Java program is in c:myAppcomfoosrcserviceMyTest.java and you want to print until c:myAppcomfoosrcservice 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.

answered Sep 27, 2012 at 10:09

JSS's user avatar

JSSJSS

2,0511 gold badge20 silver badges26 bronze badges

4

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.

answered Dec 17, 2015 at 22:29

Jan Povolný's user avatar

2

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:WINDOWSsystem32

answered Dec 25, 2015 at 14:42

SijeDeHaan's user avatar

SijeDeHaanSijeDeHaan

1752 silver badges2 bronze badges

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

answered Nov 20, 2016 at 17:04

GOXR3PLUS's user avatar

GOXR3PLUSGOXR3PLUS

6,7779 gold badges42 silver badges92 bronze badges

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 😀

Best,

answered Apr 16, 2015 at 4:39

bachden's user avatar

bachdenbachden

4413 silver badges9 bronze badges

2

For Java 11 you could also use:

var path = Path.of(".").toRealPath();

answered Mar 24, 2021 at 17:52

Volodya Lombrozo's user avatar

Volodya LombrozoVolodya Lombrozo

2,1121 gold badge14 silver badges32 bronze badges

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…

answered Jun 20, 2022 at 17:22

Adam M. Gamboa G.'s user avatar

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's user avatar

L Joey

1552 silver badges8 bronze badges

answered Feb 2, 2011 at 5:37

MJB's user avatar

MJBMJB

9,3126 gold badges34 silver badges49 bronze badges

3

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

answered May 18, 2020 at 0:54

Tonecops's user avatar

1

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:Windowssystem32, 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:Windowssystem32, 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.

answered Sep 15, 2020 at 22:20

Ted's user avatar

2

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

answered Jan 25, 2021 at 6:53

Avon97's user avatar

Avon97Avon97

4712 bronze badges

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's user avatar

Mainz007

5335 silver badges16 bronze badges

answered May 31, 2021 at 10:10

Andrew Mititi's user avatar

3

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

answered Jan 7, 2022 at 16:58

Wortig's user avatar

WortigWortig

8322 gold badges11 silver badges35 bronze badges

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.

answered Mar 2 at 23:39

Adam D.'s user avatar

Adam D.Adam D.

1511 silver badge4 bronze badges

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

answered Mar 31, 2015 at 19:35

VenerableAgents's user avatar

VenerableAgentsVenerableAgents

6471 gold badge8 silver badges16 bronze badges

1

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

answered Jan 3, 2015 at 23:10

Marko Stojkovic's user avatar

Marko StojkovicMarko Stojkovic

3,2054 gold badges19 silver badges20 bronze badges

Let’s say I have my main class in C:UsersJustianDocuments. How can I get my program to show that it’s in C:UsersJustianDocuments?

Hard-Coding is not an option- it needs to be adaptable if it’s moved to another location.

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

The Guy with The Hat's user avatar

asked Jun 30, 2010 at 20:56

Justian Meyer's user avatar

Justian MeyerJustian Meyer

3,5939 gold badges34 silver badges53 bronze badges

7

One way would be to use the system property System.getProperty("user.dir"); this will give you “The current working directory when the properties were initialized”. This is probably what you want. to find out where the java command was issued, in your case in the directory with the files to process, even though the actual .jar file might reside somewhere else on the machine. Having the directory of the actual .jar file isn’t that useful in most cases.

The following will print out the current directory from where the command was invoked regardless where the .class or .jar file the .class file is in.

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

if you are in /User/me/ and your .jar file containing the above code is in /opt/some/nested/dir/
the command java -jar /opt/some/nested/dir/test.jar Test will output current dir = /User/me.

You should also as a bonus look at using a good object oriented command line argument parser.
I highly recommend JSAP, the Java Simple Argument Parser. This would let you use System.getProperty("user.dir") and alternatively pass in something else to over-ride the behavior. A much more maintainable solution. This would make passing in the directory to process very easy to do, and be able to fall back on user.dir if nothing was passed in.

answered Jun 30, 2010 at 21:12

3

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

Update as per the comment of the OP:

I want to dump a bunch of CSV files in a folder, have the program recognize all the files, then load the data and manipulate them. I really just want to know how to navigate to that folder.

That would require hardcoding/knowing their relative path in your program. Rather consider adding its path to the classpath so that you can use ClassLoader#getResource()

File classpathRoot = new File(classLoader.getResource("").getPath());
File[] csvFiles = classpathRoot.listFiles(new FilenameFilter() {
    @Override public boolean accept(File dir, String name) {
        return name.endsWith(".csv");
    }
});

Or to pass its path as main() argument.

answered Jun 30, 2010 at 21:06

BalusC's user avatar

BalusCBalusC

1.1m371 gold badges3601 silver badges3546 bronze badges

16

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

Prints something like:

/path/to/current/directory
/path/to/current/directory/.

Note that File.getCanonicalPath() throws a checked IOException but it will remove things like ../../../

answered Jun 5, 2012 at 14:57

cyber-monk's user avatar

cyber-monkcyber-monk

5,4506 gold badges32 silver badges42 bronze badges

0

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

Bill the Lizard's user avatar

answered May 15, 2013 at 13:51

Peter De Winter's user avatar

Peter De WinterPeter De Winter

1,1732 gold badges15 silver badges27 bronze badges

2

If you want to get your current working directory then use the following line

System.out.println(new File("").getAbsolutePath());

answered Feb 16, 2018 at 3:28

rjrajsaha's user avatar

rjrajsaharjrajsaha

791 silver badge5 bronze badges

I just used:

import java.nio.file.Path;
import java.nio.file.Paths;

Path workingDirectory=Paths.get(".").toAbsolutePath();

answered Apr 28, 2015 at 23:54

user3696181's user avatar

3

If you want the absolute path of the current source code, my suggestion is:

String internalPath = this.getClass().getName().replace(".", File.separator);
String externalPath = System.getProperty("user.dir")+File.separator+"src";
String workDir = externalPath+File.separator+internalPath.substring(0, internalPath.lastIndexOf(File.separator));

answered Jul 29, 2013 at 12:17

jmamatos's user avatar

jmamatosjmamatos

591 silver badge1 bronze badge

2

Who says your main class is in a file on a local harddisk? Classes are more often bundled inside JAR files, and sometimes loaded over the network or even generated on the fly.

So what is it that you actually want to do? There is probably a way to do it that does not make assumptions about where classes come from.

answered Jun 30, 2010 at 21:03

Michael Borgwardt's user avatar

Michael BorgwardtMichael Borgwardt

341k78 gold badges481 silver badges718 bronze badges

4

Getting the path of current directory is often required when you need to access some files from code generally for reading text or properties files.

This article will explain 4 different ways to get the path of current working directory in java or from java code.

Method 1: Using System property
Java has defined some properties which are used to get information about its environment. One of such property is user.dir which gives the path of current working directory.

In order to retrieve the value of java properties, getProperty() method of java.lang.System class is used. This method is static and takes a string argument, which is the name of property.
Example,

String currentPath = System.getProperty("user.dir");
System.out.println("Current path is:: " + currentPath);

If you run this code from an IDE such as eclipse, then it will return the absolute path of the current project.

Method 2: Using File class
java.io.File class has a constructor which takes a string argument. This argument represents the path to which the file object points.

Providing an empty path means that the file object is pointed to the current folder. Invoke getAbsolutePath() on the file object to get the complete path of current directory as shown below.

// create file object for current folder
File file = new File("");
String currentPath = file.getAbsolutePath();
System.out.println("Current path is:: " + currentPath);

Method 3: Using Paths
java.nio.file.Paths class introduced in java 7 is a utility class that contains static methods related to paths. It has a static get() method which takes a string argument representing a file path and returns an object of java.nio.file.Path.

Supplying empty string to get() means the current working directory.
Path object points to a physical file and its toAbsolutePath() method returns another Path object containing the absolute path of the file.

Invoke toString() method on this Path object to get the path of current working directory.
Java program code for this method is given below.

Path currentDirectoryPath = Paths.get("").toAbsolutePath();
String currentPath = currentDirectoryPath.toString();
System.out.println("Current directory path:: " + currentPath);

Method 4: Using FileSystems class
For dealing with file system, java provides a class java.nio.file.FileSystem. Object of FileSystem can be retrieved using java.nio.file.FileSystems class using its static getDefault() method.

FileSystem has a getPath() method which takes a string argument representing the path of a file.
Supplying it an empty string means the current directory.
getPath() returns an object of Path and you can use its toAbsolutePath() method to get the full path of current directory.
Example,

FileSystem fileSystem = FileSystems.getDefault();
Path path = fileSystem.getPath("").toAbsolutePath()
String currentDirectoryPath = path.toString();

Above code can be written as one-liner

String currentDirectoryPath = FileSystems.getDefault().
                                          getPath("").
                                          toAbsolutePath().
                                          toString();

Hope the article was useful, click the clap below if you liked it.

1. Overview

It’s an easy task to get the current working directory in Java, but unfortunately, there’s no direct API available in the JDK to do this.

In this tutorial, we’ll learn how to get the current working directory in Java with java.lang.System, java.io.File, java.nio.file.FileSystems, and java.nio.file.Paths.

2. System

Let’s begin with the standard solution using System#getProperty, assuming our current working directory name is Baeldung throughout the code:

static final String CURRENT_DIR = "Baeldung";
@Test
void whenUsingSystemProperties_thenReturnCurrentDirectory() {
    String userDirectory = System.getProperty("user.dir");
    assertTrue(userDirectory.endsWith(CURRENT_DIR));
}

We used a Java built-in property key user.dir to fetch the current working directory from the System‘s property map. This solution works across all JDK versions.

3. File

Let’s see another solution using java.io.File:

@Test
void whenUsingJavaIoFile_thenReturnCurrentDirectory() {
    String userDirectory = new File("").getAbsolutePath();
    assertTrue(userDirectory.endsWith(CURRENT_DIR));
}

Here, the File#getAbsolutePath internally uses System#getProperty to get the directory name, similar to our first solution. It’s a nonstandard solution to get the current working directory, and it works across all JDK versions.

4. FileSystems

Another valid alternative would be to use the new java.nio.file.FileSystems API:

@Test
void whenUsingJavaNioFileSystems_thenReturnCurrentDirectory() {
    String userDirectory = FileSystems.getDefault()
        .getPath("")
        .toAbsolutePath()
        .toString();
    assertTrue(userDirectory.endsWith(CURRENT_DIR));
}

This solution uses the new Java NIO API, and it works only with JDK 7 or higher.

5. Paths

And finally, let’s see a simpler solution to get the current directory using java.nio.file.Paths API:

@Test
void whenUsingJavaNioPaths_thenReturnCurrentDirectory() {
    String userDirectory = Paths.get("")
        .toAbsolutePath()
        .toString();
    assertTrue(userDirectory.endsWith(CURRENT_DIR));
}

Here, Paths#get internally uses FileSystem#getPath to fetch the path. It uses the new Java NIO API, so this solution works only with JDK 7 or higher.

6. Conclusion

In this tutorial, we explored four different ways to get the current working directory in Java. The first two solutions work across all versions of the JDK whereas the last two work only with JDK 7 or higher.

We recommend using the System solution since it’s efficient and straight forward, we can simplify it by wrapping this API call in a static utility method and access it directly.

The source code for this tutorial is available over on GitHub – it is a Maven-based project, so it should be easy to import and run as-is.

% Path

Интерфейс: java.nio.file.Path

Описание

Представляет собой абстракцию пути к элементу файловой системы (файлу, каталогу или чему-то ещё). Понятие “файловой
системы” здесь можно трактовать достаточно широко, и это не обязательно именно дисковая файловая система. Например,
в стандартной библиотеке есть реализация, представляющая ZIP-архив как файловую систему.

Класс Path предназначен только для манипуляции путями как синтаксическими конструкциями, и вовсе не обязательно, что
файл (или другой элемент ФС), на который указывает путь, действительно существует. Объект Path проще всего
рассматривать как ссылку на элемент ФС, которая сама по себе не умеет работать с тем, на что ссылается. Для операций с
самой ФС используется класс Files, принимающий параметры типа Path.

Здесь мы рассмотрим только операции со стандартной ФС.

Создание путей

Чтобы создать объект типа Path с нуля, используется статический метод get в классе Paths:

static Path get(String first, String... more)

Этот метод принимает один и более компонентов пути, разбивает их на отдельные подкомпоненты по платформозависимым
разделителям (/ для Unix, для Windows), и из полученных компонентов создаёт объект типа Path.

Например, на платформе Windows все приведённые примеры эквивалентны:

Path p1 = Paths.get("C:/windows/explorer.exe");
Path p2 = Paths.get("C:\windows\explorer.exe");
Path p3 = Paths.get("C:\windows", "explorer.exe");
Path p4 = Paths.get("C:", "windows", "explorer.exe");

Обратите внимание, что обратная косая черта должна экранироваться. К сожалению, в Java нет способа отменить
экранирование для более короткой записи Windows-путей.

Объекты класса Path являются неизменяемыми. Все операции с путями возвращают новые объекты Path.

Строковое представление

У класса Path есть вполне привычный метод toString(), возвращающий представление пути в виде строки, используя
системный разделитель компонентов пути.

Path path = Paths.get("C:\windows\system32");
System.out.println(path);
// Или, что то же самое:
// System.out.println(path.toString())

Результат:

Абсолютные и относительные пути

Приведённый выше пример пути является абсолютным путём, потому что он начинается с корня ФС. Абсолютный путь всегда
однозначно идентифицирует элемент ФС, независимо от того, какой каталог является текущим каталогом программы.

В Unix абсолютные пути начинаются с косой черты, обозначающей корень файловой системы, а в Windows — с буквы
диска. Например, следующие два пути являются абсолютными:

Path unixAbsPath = Paths.get("/usr/bin/firefox");
Path winAbsPath = Paths.get("C:\Program Files\Mozilla Firefox\firefox.exe");

Относительные пути — это пути, ведущие отсчёт от какого-то каталога. По умолчанию при выполнении операций ФС
над относительными путями они разрешаются относительно текущего каталога (current directory), также называемого
рабочим каталогом (working directory). Метод toAbsolutePath() позволяет преобразовать относительный путь в
абсолютный, при этом он разрешается относительно текущего каталога.

Пусть в каталоге /home/user/java лежит файл AbsolutePath.class, откомпилированный из такого файла:

import java.nio.file.Path;
import java.nio.file.Paths;

public class AbsolutePath {
	public static void main(String[] args) {
		Path relPath = Paths.get("lib/opencsv.jar");
		Path absPath = relPath.toAbsolutePath();
		System.out.println(absPath);
	}
}

Тогда мы получим такой результат при запуске этой программы из командной строки (напомним, что команда cd
устанавливает текущий каталог):

$ cd /home/user/java
$ java AbsolutePath
/home/user/java/lib/opencsv.jar
$ cd /tmp
$ java -cp /home/user/java AbsolutePath
/tmp/lib/opencsv.jar

При задании относительных путей из соображений переносимости нежелательно использовать разделитель путей Windows ,
если только не известно точно, что программа будет запускаться только под Windows. Windows понимает разделитель путей
Unix /, а вот обратное неверно. Ещё правильнее использовать статический метод Paths.get с несколькими параметрами,
чтобы не завязываться на конкретный платформозависимый разделитель, а в случае необходимости всё-таки получить этот
разделитель в виде строки можно воспользоваться методом FileSystem.getSeparator:

System.out.println(FileSystem.getDefault().getSeparator());
// Печатает / под Unix и  под Windows

Для преобразования относительного пути в абсолютный относительно не текущего каталога, а какого-то другого, можно
воспользоваться методом resolve. Его нужно вызвать у того пути, относительно которого мы разрешаем относительный путь.
У метода resolve есть две версии: одна принимает Path, а вторая принимает String и рассматривает эту строку как
путь, который предстоит разрешить.

Path resolve(Path other)

Path resolve(String other)

Например:

Path configDir = Paths.get("/etc");
System.out.println(configDir.resolve("passwd"));
// /etc/passwd
Path apacheConf = Paths.get("apache2", "apache2.conf");
System.out.println(configDir.resolve(apacheConf));
// /etc/apache2/apache2.conf

Обратную задачу решает метод relativize, превращающий переданный параметром абсолютный путь в относительный
относительно того пути, у которого этот метод вызывается.

Path relativize(Path other)

Например:

Path homeDir = Paths.get("/home/user");
Path movie = Paths.get("/home/user/Videos/JavaLesson.mkv");
System.out.println(homeDir.relativize(movie));
// Videos/JavaLesson.mkv

Переход вверх и вниз по иерархии ФС

Метод getParent возвращает родительский элемент ФС (как правило, каталог), или null, если такового не существует.

Path getParent()

Например:

System.out.println(Paths.get("C:\windows").getParent());
// C:
System.out.println(Paths.get("C:").getParent());
// null

А метод resolve можно использовать не только для абсолютизации путей, но и для получения пути к какому-либо элементу
каталога или какого-то его подкаталога ещё ниже по иерархии ФС:

Paths.get("C:\windows").resolve("explorer.exe")
// C:windowsexplorer.exe
Paths.get("C:\windows").resolve("system32\user32.dll")
// C:windowssystem32user32.dll

Есть также метод resolveSibling, позволяющий получить “сестринский” элемент ФС, то есть разрешающий переданный путь
относительно родительского элемента ФС.

Path resolveSibling(Path other)

Path resolveSibling(String other)

Например, он позволяет получить путь к другому файлу в том же каталоге:

Path dll = Paths.get("C:\windowssystem32\user32.dll")
System.out.println(dll.resolveSibling("kernel32.dll")
// C:windowssystem32kernel32.dll

Доступ к компонентам пути

Методы getNameCount и getName позволяют пройтись по всем компонентам пути, представленного объектом Path. Эти
компоненты сами имеют тип Path.

int getNameCount()

Path getName(int index)

Например:

Path path = Paths.get("C:\windowsexplorer.exe");

for (int i = 0; i < path.getNameCount(); i++) {
	System.out.println(path.getName(i));
}

Результат:

Кроме того, класс Path реализует интерфейс Iterable<Path> и, следовательно, поддержку цикла for-each, поэтому то же
самое делает и такой код:

for (Path component: path) {
	System.out.println(component);
}

и даже

path.forEach(System.out::println);

Получение имени файла и каталога

Метод getFileName возвращает путь из одного компонента, соответствующего последнему компоненту исходного пути. Обычно
это имя файла или другого элемента ФС, на который указывает объект Path. Обратите внимание, что этот метод возвращает
Path, а не String.

Path getFileName()

Например:

Paths.get("/home/user/Pictures/kitty.jpg").getFileName()
// kitty.jpg
Paths.get("C:\gamesWorld of Warcraft").getFileName()
// World of Warcraft

Как мы знаем, получить путь к каталогу, в котором находится файл, можно с помощью getParent:

Paths.get("/home/user/Pictures/kitty.jpg").getParent()
// /home/user
Paths.get("C:\gamesWorld of Warcraft").getParent()
// C:games

Работа с расширениями

К сожалению, класс Path сам по себе не предоставляет удобных способов работы с расширениями. В некотором смысле это
логично, ведь понятие расширения существует только для приложений, работающих с файлами, а для самой ФС это всего лишь
часть имени файла. Чтобы отделить расширение, придётся работать с именем файла как со строкой.

Прежде всего эту строку нужно получить:

String fileNameStr = path.getFileName().toString();

После чего работать с расширениями можно обычными строковыми методами:

boolean isPng = fileNameStr.toLowerCase().endsWith(".png");

Обратите внимание на вызов toLowerCase. Это гарантирует, что мы проверим имя файла на нужное расширение в любом
регистре (.png, .PNG, .Png и т.д.).

У интерфейса Path тоже есть метод endsWith, но он проверяет, заканчивается ли путь данным компонентом пути, а не
заканчивается ли строка имени файла данной строкой. Не путайте!

Paths.get("/home/user/report.txt").endsWith("report.txt")  // true
Paths.get("report.txt").endsWith(".txt")  // false
Paths.get("report.txt").toString().endsWith(".txt")  // true

Наконец, можно написать свой метод, который возвращает расширение имени файла или пустую строку, если у имени файла
нет расширения:

public String getExtension(Path path) {
	String fileNameStr = path.getFileName().toString();
	int lastDot = fileNameStr.lastIndexOf('.');
	
	if (lastDot == -1) {
		return "";
	} else {
		return fileNameStr.substring(lastDot + 1);
	}
}

Взаимодействие со старыми API

Интерфейс Path появился в Java 7. Старые API, спроектированные для Java 6 и ниже, обычно используют вместо него более
старый класс File, существовавший аж в Java 1.0. Он менее удобен, чем Path, потому что поддерживает только
стандартную ФС и нарушает принцип единственности ответственности, сочетая в себе методы для синтаксической манипуляции
путями и методы доступа к ФС.

Если нужно передать объект Path в старое API, используйте метод toFile:

File toFile()

И, получая объекты File из старого API, преобразуйте их в Path:

Path toPath()

К примеру, класс ImageIO, отвечающий за загрузку, сохранение и преобразование изображений, к сожалению, так и не был
обновлён для поддержки параметров типа Path. Вот так с помощью ImageIO можно преобразовать любой поддерживаемый
формат изображений в формат PNG:

Path source = Paths.get("/home/user/Pictures/diagram.bmp");
BufferedImage image = ImageIO.read(source.toFile());

Path dest = Paths.get("/home/user/Pictures/diagram.png");
ImageIO.write(image, "bmp", dest.toFile());

Добавить комментарий