Getting the Current Working Directory in Java

Introduction
In this section, you will learn how to get the current working directory. The
current working directory that means where your program run. This program shows
the current directory name when your program run. Following methods are invoked for this
purpose :
System.getProperty("user.dir");
This is the getProperty()
method of the System
class of the
java.lang package returns the system properties according to the indicated
argument. Here, the mentioned indicated argument is "user.dir"
which indicates about the getting the current directory name.
Here is the code of the program :
import java.io.*;
public class GetCurrentDir{
private static void dirlist(String fname){
File dir = new File(fname);
System.out.println("Current Working Directory : "+ dir);
}
public static void main(String[] args){
String currentdir = System.getProperty("user.dir");
dirlist(currentdir);
}
}
|
Output of the program
C:\nisha>javac GetCurrentDir.java
C:\nisha>java GetCurrentDir
Current Working Directory : C:\nisha
C:\nisha> |
Download this example.

|
Current Comments
2 comments so far (post your own) View All Comments Latest 10 Comments:dear sir
how to select cdrom at program run time using java.
Posted by ganesh on Tuesday, 06.3.08 @ 20:10pm | #61976
It works fine on Windows systems, but how do you get the working directory in Linux?
Posted by buri on Friday, 12.14.07 @ 18:50pm | #42277