Java - Manipulate directory and file path in portable way

By xngo on February 27, 2019

Directory path separtor are different in MS Windows and in Linux. In MS Windows, it uses backward slash(\), whereas in Linux, it uses forward slash(/).

The code below shows how to manipulate directory and file path in portable way. We simply use File.separator that is provided by Java. It will set the correct directory path separator depending on your operating system.

import java.io.File;
import java.io.IOException;
 
public class DirFileHandling
{
  public static void main(String[] args)
  {
    // Get current directory path
    File oFile = new File(".");
    String sCurrDirPath = "";
    try
    {
      sCurrDirPath = oFile.getCanonicalPath();
      System.out.println(sCurrDirPath);
    }
    catch(IOException ex)
    {
      System.out.println(ex.getMessage());
    }
 
    // Create the path of a new sub-directory.
    String sNewDirPath = sCurrDirPath + File.separator  + "NewDirName";
    System.out.println(sNewDirPath);
 
    // Create the path of a file under the sub-directory.
    String sNewFilePath = sCurrDirPath + File.separator + "NewDirName"+ File.separator + "NewFileName.txt";
    System.out.println(sNewFilePath);
 
  }
 
}

Output ran from Linux

/home
/home/NewDirName
/home/NewDirName/NewFileName.txt

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.