Advertisement
Advertisement


How to get the current working directory in Java?


Question

I want to access my current working directory using java.

My code :

 String current = new java.io.File( "." ).getCanonicalPath();
        System.out.println("Current dir:"+current);
 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 C drive is not my current directory.

How to get the current directory ?

2020/04/16
1
1055
4/16/2020 6:37:12 AM


See: http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

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 relative path is: " + s);

This outputs Current relative 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.

2016/05/10

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

import java.nio.file.Paths;

Paths.get(".").toAbsolutePath().normalize().toString();
2016/05/25

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();
2020/03/05

This is the solution for me

File currentDir = new File("");
2013/05/28

I've found this solution in the comments which is better than others and more portable:

String cwd = new File("").getAbsolutePath();

Or even

String cwd = Paths.get("").toAbsolutePath();
2020/03/17

Source: https://stackoverflow.com/questions/4871051
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]