Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current working directory in Java?

Tags:

java

java-io

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?

like image 763
Qazi Avatar asked Feb 02 '11 05:02

Qazi


2 Answers

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.

like image 36
geoO Avatar answered Sep 28 '22 01:09

geoO


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.

like image 122
Anuj Patel Avatar answered Sep 28 '22 01:09

Anuj Patel