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.

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

Output ran from Linux


About the author

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