Java IO Tutorial

How to get file path separator in Java

For file path or directory separator, the Unix system introduced the slash character / as directory separator, and the Microsoft Windows introduced backslash character \ as the directory separator. In a nutshell, this is / on UNIX and \ on Windows.

In Java, we can use the following three methods to get the platform-independent file path separator.

  1. System.getProperty("file.separator")
  2. FileSystems.getDefault().getSeparator() (Java NIO)
  3. File.separator Java IO

1. System Property

Get the file path separator via the system Properties file.separator.

GetFileSeparator1.java

package com.mkyong.io.howto;

public class GetFileSeparator {

    public static void main(String[] args) {

        // unix / , windows \
        String separator = System.getProperty("file.separator");
        System.out.println(separator);

    }

}

2. Java NIO

Java 7, NIO FileSystems.getDefault().getSeparator().

GetFileSeparator2.java

package com.mkyong.io.howto;

import java.nio.file.FileSystems;

public class GetFileSeparator2 {

    public static void main(String[] args) {

        // unix / , windows \
        String separator = FileSystems.getDefault().getSeparator();
        System.out.println(separator);

    }

}

3. Java IO

Java IO File.separator example.

GetFileSeparator3.java

package com.mkyong.io.howto;

import java.io.File;

public class GetFileSeparator3 {

    public static void main(String[] args) {

        // unix / , windows \
        String separator = File.separator;
        System.out.println(separator);

    }

}

4. Which One?

For System.getProperty("file.separator"), we can override the value by System.setProperty() or command line -Dfile.separator. Both File.separator and FileSystems.getDefault().getSeparator() will returns the same separator.

Read on this Legacy File I/O Code drawbacks, picks the Java NIO FileSystems.getDefault().getSeparator().

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-io

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments