Here’s two “how to” Java examples to construct a file path :

  1. Check the operating system and create the file separator manually. (Not recommend)
  2. Let’s Java do all the job ~ File.separator. (Best Practice)

File.separator is always recommended, because it will check your OS and display the correct file separator automatically, For example,

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

Manual file separator example

A classic way to construct a file path manually, which is not recommended.

package com.mkyong.file;
 
import java.io.File;
import java.io.IOException;
 
public class FilePathExample 
{
    public static void main( String[] args )
    {	
    	try {
 
    	  String filename = "testing.txt";
    	  String finalfile = "";
    	  String workingDir = System.getProperty("user.dir");
 
    	  String your_os = System.getProperty("os.name").toLowerCase();
    	  if(your_os.indexOf("win") >= 0){
    		  finalfile = workingDir + "\\" + filename;
    	  }else if(your_os.indexOf( "nix") >=0 || your_os.indexOf( "nux") >=0){
    		  finalfile = workingDir + "/" + filename;
    	  }else{
    		  finalfile = workingDir + "{others}" + filename;
    	  }
 
    	  System.out.println("Final filepath : " + finalfile);
    	  File file = new File(finalfile);
 
	  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, just one line code can do all the checking above.

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

Reference

  1. http://java.sun.com/javase/6/docs/api/java/io/File.html
  2. http://www.mkyong.com/java/how-to-get-the-current-working-directory-in-java/
  3. http://lopica.sourceforge.net/os.html
  4. http://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/
Any Java questions or problems? please post at this JavaNullPointer.com forum, see you there ~