In this section we will be showing examples on how to get the current directory in java. Basically we will explore getAbsolutePath() method of File class under java.lang package. One other solution is get it using the System.getProperty.

Get Current Directory in java using getAbsolutePath()

This sample java source code demonstrates usage of getAbsolutePath() in getting the current directory.

package com.javatutorialhq.tutorial;

import java.io.File;

public class GetCurrentDirectory {

	/**
	 * This java sample code shows
	 * how to get the current working directory
	 * using getAbsolutePath() method of File class
	 * Property of javatutorialhq.com
	 * All Rights Reserved
	 * Version 1.0
	 * 07/01/2012
	 */
	public static void main(String[] args) {
		String currentDirectory;
		File file = new File(".");
		currentDirectory = file.getAbsolutePath();
		System.out.println("Current working directory : "+currentDirectory);
	}
}

Sample output:

Current working directory : C:\Users\ryan\workspace\JavaBasics\.

 

Get Current Directory in java using Property user.dir

In this java sample source code we will be illustrating on how to get the current working directory by invoking getProperty() method and passing property name user.dir.

package com.javatutorialhq.tutorial;

import java.io.File;

public class GetCurrentDirectory {

	/**
	 * This java sample code shows
	 * how to get the current working directory
	 * using the property user.dir
	 * Property of javatutorialhq.com
	 * All Rights Reserved
	 * Version 1.0
	 * 07/01/2012
	 */
	public static void main(String[] args) {
		String currentDirectory;
		currentDirectory = System.getProperty("user.dir");
		System.out.println("Current working directory : "+currentDirectory);
	}
}