How to get current working directory in java

In this post, we will see how to get current working directory in java.
There are two ways to do it.
  • Using property user.dir
  • Using getAbsolutePath()

Using property user.dir

We can use System.getProperty("user.dir") to get current working directory path.
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("--------------");
	}
}

When I ran above program, I got below output:
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir

Using getAbsolutePath()

We can use file.getAbos
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("--------------");
	}
}

When I ran above program, I got below output:
Current working directory is : /Users/Arpit/workspaceBlogFeb/GetCurrentWorkingDir/.




    Written by Arpit:

    If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

     

    Java tutorial for beginners Copyright © 2012