Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Java-get-example Get current working directory in Java

Related Tutorials


 
 

Share on Google+Share on Google+

Get current working directory in Java

Advertisement
This section java program explain how to get the current working directory(CWD).

Get current working directory in Java

In this section we will discuss about how to get the the current working directory in java. Current working directory means the current working directory where java program execute. In java it is easy to get the current working directory,  it can be retrieved by system properties function :

String cwd = System.getProperty("user.dir");

A Properties object of System class describes the configuration of the current working environment. It also include information about current user , the current version of the Java runtime, and the character used to separate component of a file path name. Here, "user.dir" is a user directory

How to get current directory in Java with Example

public class CurrentworkingDirectory {
		 
	    public static void main(String args[]) {
	     
	        String cwd = System.getProperty("user.dir");
	       System.out.println(" "); 
                         System.out.println("Current working directory in Java : " + cwd);
	     
	    }
	}

Output from the program :

Download SourceCode

There are two types of path in java they are as follows :

  • Canonical path
  • Absolute path.

We can get the canonical path by calling getCannonicalPath(),  and for absolute path by calling getAbsolutePath() method. Now here is the example using these methods :

import java.io.File;
import java.io.IOException;

public class CurrentworkingDirectory2 {
		 
	    public static void main(String args[]) throws IOException {
	     
	        File file =new File(".");
	        System.out.println(" ");
	        System.out.println("Canonical path = "+file.getAbsolutePath());
	        System.out.println("Absolute path = "+file.getCanonicalPath());
	     
	    }
	}

Output from the program :

Download SourceCode

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 25, 2013

Related Tutorials

Discuss: Get current working directory in Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com