Search Java Programs

Friday, February 5, 2010

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.

import java.io.*;

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

has been created 
                             to the specified location");
      System.out.println("The absolute path of the file is: "
                +f.getAbsolutePath());      
    }
} 
Output of the program:
C:\nisha>javac PathFile.java

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
C:\nisha>
Download this Program
Another program set the dynamic path using File.separator given below:


import java.io.*;

 
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.

No comments:

Post a Comment

Website Design by Mayuri Multimedia