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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With