File.separator vs. File.pathSeparator

27,249

java.io.File class contains four static separator variables. For better understanding, Let's understand with the help of some code

  1. separator: Platform dependent default name-separator character as String. For windows, it’s ‘\’ and for unix it’s ‘/’
  2. separatorChar: Same as separator but it’s char
  3. pathSeparator: Platform dependent variable for path-separator. For example PATH or CLASSPATH variable list of paths separated by ‘:’ in Unix systems and ‘;’ in Windows system
  4. pathSeparatorChar: Same as pathSeparator but it’s char

Note that all of these are final variables and system dependent.

Here is the java program to print these separator variables. FileSeparator.java

import java.io.File;

public class FileSeparator {

    public static void main(String[] args) {
        System.out.println("File.separator = "+File.separator);
        System.out.println("File.separatorChar = "+File.separatorChar);
        System.out.println("File.pathSeparator = "+File.pathSeparator);
        System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
    }

}

Output of above program on Unix system:

File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :

Output of the program on Windows system:

File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;

To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.

Here is the code snippet showing how to use separators correctly.

//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");
Share:
27,249
Evorlor
Author by

Evorlor

Hello.

Updated on January 03, 2020

Comments

  • Evorlor
    Evorlor over 4 years

    File has the static Strings separator and pathSeparator. The separator is a "default name-separator character" and the pathSeparator is a "path-separator character".

    What is the difference? Is there a time when one is preferable to the other?

  • Marcello Grechi Lins
    Marcello Grechi Lins about 7 years
    pathSeparator is SO missleading... Why not make it pathVariableSeparator or classpathSeparator ?
  • Well Smith
    Well Smith about 6 years
    Agree @MarcelloGrechiLins. So misleading name. Thanks Evorlor for asking this question.