Java - File Path Separator

Introduction

Different operating systems use a different character to separate pathes in a pathname.

Windows uses a backslash \ as separator in a pathname, whereas UNIX uses a forward slash /.

File.separatorChar is the system-dependent name separator character.

You can use the File.separatorChar constant to get the name separator as a character.

The following code used the name separator constant of the File class to build the following pathname:

printFilePath(".." + File.separator + "notes.txt");

Demo

import java.io.File;
import java.io.IOException;

public class Main {
  public static void main(String[] args) {
    printFilePath(".." + File.separator + "notes.txt");
  }//  ww w . ja  v  a2 s  . c  o  m

  public static void printFilePath(String pathname) {
    File f = new File(pathname);
    System.out.println("Absolute Path: " + f.getAbsolutePath());
    try {
      System.out.println("Canonical Path: " + f.getCanonicalPath());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Result

Related Topic