Tuesday, 29 April 2014

Current Working Directory in Java

In Java, You can get the Present working directory in many ways. Below are some of the Examples.

Program 1
class CurrentDir{

 static String getPWD(){
  return System.getProperty("user.dir");
 }
 
 public static void main(String args[]){
  System.out.println(getPWD());
 }
}

Output
C:\Examples

Program 2
import java.io.*;
class CurrentDir{

 static String getPWD()throws Exception{
   String current = new File( "." ).getCanonicalPath();
   return current;
 }
 
 public static void main(String args[])throws Exception{
  System.out.println(getPWD());
 }
}

Output
C:\Examples 

Program 3
import java.io.*;
class CurrentDir{
 String getPWD()throws Exception{
   return this.getClass().getClassLoader().getResource("").getPath();
 }
 
 public static void main(String args[])throws Exception{
  CurrentDir obj1 = new CurrentDir();
  System.out.println(obj1.getPWD());
 }
}

Output
C:\Examples

Program 4
import java.nio.file.Paths;
class CurrentDir{
 String getPWD()throws Exception{
   return Paths.get("").toAbsolutePath().toString();
 }
 
 public static void main(String args[])throws Exception{
  CurrentDir obj1 = new CurrentDir();
  System.out.println(obj1.getPWD());
 }
}
Output
C:\Examples


Program 5
import java.net.*;
class CurrentDir{
 String getPWD()throws Exception{
   URL location;
   location = CurrentDir.class.getProtectionDomain().getCodeSource().getLocation();
   return location.getFile();
 }
 
 public static void main(String args[])throws Exception{
  CurrentDir obj1 = new CurrentDir();
  System.out.println(obj1.getPWD());
 }
}

Output
C:\Examples 
 
                                                             Home

No comments:

Post a Comment