How to use Java File separator, separatorChar

The directory separator in Unix operating systems is a slash (right direction) – an example is /.

The directory separator in the Windows operating system is a slash (left direction) – an example is \.

It is important to understand in what environment it is correct to use a slash, because it can be platform dependent. The Java programming language provides several development methods that are independent of the operating system.

1) FileSystems.getDefault().getSeparator()

2) System.getProperty(“file.separator”)

3) File.separator

1. Java NIO – FileSystems.getDefault().getSeparator()

import java.nio.file.FileSystems;

public class FileSeparatorExample {

    public static void main(String[] args) {
	String separator = FileSystems.getDefault().getSeparator();
        System.out.println(separator);
    }

}

output

/ (for unix)
\ (for windows)

2. System.getProperty(“file.separator”)

public class FileSeparatorExample {

    public static void main(String[] args) {
        String separator = System.getProperty("file.separator");
        System.out.println(separator);
    }

}

output

/ (for unix)
\ (for windows)

3. Java IO – File.separator

import java.io.File;

public class FileSeparatorExample {

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

}

output

/ (for unix)
\ (for windows)

What is File.separatorChar

The separatorChar value is the same as File.Seperator , but it’s important to understand that it’s a character, not a string. So the output of File.separatorChar is forward slash (/) for unix and backslash (\) for windows.

File.separatorChar Example

import java.io.File;

public class FileSeparatorExample {

    public static void main(String[] args) {
	System.out.println(File.separatorChar);
    }

}

output

/ (for unix)
\ (for windows)

 

Rate article
ASJAVA.COM
Add a comment

Your email address will not be published. Required fields are marked *