Share on Google+Share on Google+

Java Construct File Path

In this section we will discuss about how to construct file path in Java.

Java Construct File Path

In this section we will discuss about how to construct file path in Java.

A file path can be constructed manually or by a Java program. It is best practice to construct a file path in Java by a Java Program. When you will construct a file path manually the path name will be system dependent because the file separator character is system dependent. For example : Windows uses '\' (separator character) and UNIX uses '/' (separator character). But, we can construct a file path system independent due to separator and separatorChar. These are public static fields of the class. So, when such fields are used to construct a file path it separates the path name by the separator what the underlying system uses to separate the file path name.


An example given below demonstrates that how to construct a file pathname by a Java program in Java. In this example I have created a Java class where I have write the code for command line input and then get the user's current working directory and uses the File.separator to apply the separator character in constructing of file pathname. Then used createNewFile() method to create a new file with the specified name in the specified directory. In this example a file name can be given at the time of execution of the class i.e. file name can be given through command line.

Source Code


public class JavaConstructFilePathnameExample
     public static void main(String args[])
          String f = args[0];
          String currDir = System.getProperty("user.dir");
          System.out.println("\n Current Working Directory = "+currDir);
          String fileName = currDir + File.separator + f;
           File file = new File(fileName);
                   System.out.println("\n File '"+file.getName()+"' already existed");
                         System.out.println("\n File '"+file.getName()+ "' created successfully ");
                         System.out.println("\n Path of '"+file.getName()+ "' file is : "+file.getAbsolutePath());
                    catch(IOException ioe)
       }// main() closed
}// class closed


When you will execute the above example you will get the output (white marked on console) as follows :

Download Source Code


Posted on: December 27, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

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.

Discuss: Java Construct File Path  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image