Skip to Content

Construct file path

  1. /*
  2.    Construct file path
  3.    This Java example shows how to construct a file path in Java using File class.
  4. */
  5.  
  6. import java.io.*;
  7.  
  8. public class ConstructFilePath {
  9.  
  10.   public static void main(String[] args) {
  11.    
  12.     /*
  13.      * To create a file path use File.separator constant defined in
  14.      * File class.
  15.      *
  16.      * Windows based machines has path like \dir1\dir2 while UNIX based machines
  17.      * has path like /dir1/dir2
  18.      */
  19.    
  20.      String filePath = File.separator + "JavaExamples" + File.separator + "IO";
  21.                
  22.     //create new File object
  23.     File file = new File(filePath);
  24.    
  25.     /*
  26.      * Please note that creating file object DOES NOT actually create a file.
  27.      * It DOES NOT have any effects on the filesystem.
  28.      */
  29.    
  30.     //display file path using getPath() method of File class.
  31.     System.out.println("File path is : " + file.getPath());
  32.        
  33.   }
  34. }
  35.  
  36. /*
  37. Output in Windows machine would be,
  38. File path is : \JavaExamples\IO
  39.  
  40. Output in UNIX machine would be,
  41. File path is : /JavaExamples/IO
  42. */