Monday 28 January 2013

Construct File Path In Java

Examples to construct a file path in Java :

Identify the operating system and create the file separator manually. (Not recommend)
Let’s Java do all the job, i.e File.separator. (Best Practice)
File.separator is always recommended, because it will check your OS and display the correct file separator automatically, and also you can use this best practice to reduce the code. For example,

Windows – Return “\”
*nix – Return “/”.

Manual file separator example
Way to construct a file path manually, which is not recommended in programming world.

package com.sanjeetpandey;
 
import java.io.File;
import java.io.IOException;
 
public class FilePath 
{
    public static void main( String[] args )
    { 
     try {
 
       String filename = "test.txt";
       String finalPath = "";
       String workingDir = System.getProperty("user.dir");
 
       String osName = System.getProperty("os.name").toLowerCase();
       if(osName.indexOf("win") >= 0){
        finalfile = workingDir + "\\" + filename;
       }else if(osName.indexOf( "nix") >=0 || your_os.indexOf( "nux") >=0){
        finalfile = workingDir + "/" + filename;
       }else{
        finalfile = workingDir + "{others}" + filename;
       }
 
       System.out.println("Final filepath : " + finalPath);
       File file = new File(finalPath);
 
   if (file.createNewFile()){
      System.out.println("Done");
   }else{
      System.out.println("File already exists!");
   }
 
     } catch (IOException e) {
      e.printStackTrace();
 }
    }
}

File.separator example
A proper way is use the File.separator, see the different below, just one line code can do all the checking above.

package com.sanjeetpandey;
 
import java.io.File;
import java.io.IOException;
 
public class FilePath 
{
    public static void main( String[] args )
    { 
     try {
 
       String filename = "test.txt";
       String finalPath = "";
       String workingDir = System.getProperty("user.dir");
 
       finalPath = workingDir + File.separator + filename;
 
       System.out.println("Final filepath : " + finalPath);
       File file = new File(finalPath);
 
   if (file.createNewFile()){
      System.out.println("Done");
   }else{
      System.out.println("File already exists!");
   }
 
     } catch (IOException e) {
      e.printStackTrace();
 }
    }
}

No comments:

Post a Comment