Share on Google+Share on Google+

Constructing a File Name path in Java

In this section, you will learn about constructing a file name path through the java program.

Constructing a File Name path 


In Java, it is possible to set dynamic path, which is helpful for mapping local  file name with the actual path of the file using the constructing filename path technique.

As you have seen, how a file is created to the current directory where the program is run. Now we will see how the same program constructs a File object from a more complicated file name, using the static constant File.separator or File.separatorCharto specify the file name in a platform-independent way. If we are using Windows platform then the value of this separator is  ' \ ' .

Lets see an example to create a file to the specified location.


public class PathFile{
  public static void main(String[] argsthrows IOException{
  File f;
  f=new File("example" + File.separator + "myfile.txt");
  System.out.println("New file \"myfile.txt\" 

has been created 
   to the specified location"
  System.out.println("The absolute path of the file is: "

Output of the program:


C:\nisha>java PathFile
New file "myfile.txt" has been created to the specified location
The absolute path of the file is: C:\nisha\example\myfile.txt


Download this Program

Another program set the dynamic path using File.separator given below:


public class ConstructingFileNamePath {
public static void main(String[] args){

    String filepath = File.separatorChar + "tapan"
+ File.separatorChar + "joshi";

    System.out.println("The path of the file is  :  " 
  + filepath

Output of the program:

C:\java>java ConstructingFileNamePath
The path of the file is : \tapan\joshi

Download this example.



Posted on: April 16, 2007 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: Constructing a File Name path in Java   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
August 29, 2011
wrong code

the above code does not working properly
June 27, 2012
This won't work

You will get IOException. Use File.mkdirs to create the path before the file.
November 12, 2012
'error in running the first program above'

Dear Sir, I get the below error when I run the program above in Netbeans editor. Error Details:-- Exception in thread "main" The system cannot find the path specified at Method) at at practicey102.main( Java Result: 1