There are four ways to do it.
Table of Contents
Using property user.dir
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package org.arpit.java2blog; /* * @Author Arpit Mandliya */ public class getCurretWorkingDirectoryMain { public static void main(String[] args) { System.out.println("--------------"); String currentWorkingDirectory; currentWorkingDirectory = System.getProperty("user.dir"); System.out.println("Current working directory is : "+currentWorkingDirectory); System.out.println("--------------"); } } |
1 2 3 |
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir |
Using getAbsolutePath()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package org.arpit.java2blog; import java.io.File; /* * @Author Arpit Mandliya */ public class getCurretWorkingDirectoryMain { public static void main(String[] args) { System.out.println("--------------"); String currentWorkingDirectory=""; // . denotes current working directory File file=new File("."); currentWorkingDirectory=file.getAbsolutePath(); System.out.println("Current working directory is : "+currentWorkingDirectory); System.out.println("--------------"); } } |
1 2 3 |
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir/. |
Using Paths.get() (Java 7+)
You can use Paths.get("")
method get current working directory in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package org.arpit.java2blog; import java.nio.file.Path; import java.nio.file.Paths; /* * @Author Arpit Mandliya */ public class getCurretWorkingDirectoryMain { public static void main(String[] args) { String currentWorkingDirectory; System.out.println("--------------"); Path currentRelativePath = Paths.get(""); String s = currentRelativePath.toAbsolutePath().toString(); currentWorkingDirectory=s.toString(); System.out.println("Current working directory is : "+currentWorkingDirectory); System.out.println("--------------"); } } |
When I ran above program, I got below output:
1 2 3 |
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir/ |
Using FileSystems.getDefault() (Java 7+)
You can use FileSystem.getDefault()
method get current working directory in java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package org.arpit.java2blog; import java.nio.file.FileSystems; import java.nio.file.Path; /* * @Author Arpit Mandliya */ public class getCurretWorkingDirectoryMain { public static void main(String[] args) { String currentWorkingDirectory; System.out.println("--------------"); Path path = FileSystems.getDefault().getPath("").toAbsolutePath(); currentWorkingDirectory=path.toString(); System.out.println("Current working directory is : "+currentWorkingDirectory); System.out.println("--------------"); } } |
When I ran above program, I got below output:
1 2 3 |
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir/ |
That’s all about how to get current working directory in java.