file separator for all platform in java

This example shows you how to get the correct file separator for specific platform like Window or Linux.

You can create application in any platform like window or Linux, but to make sure to run application in any platform some of code we need to make sure that it run smoothly, The example can be here file separator in different platform, because the file separator is different in Window and Linux, Windows use “\” (back slash) while Linux use “/” (forward slash).

So if you need to use the file separator in your application you can get the file separator based on platform it is running.

To avoid manual checking for the operating system we can get the file separator symbol from the system property using the file.separator key.

And the second way to get the operating system file separator you can use the File.separator attribute.

Below is the example code.

package com.java.connect.io;
import java.io.File;
//file separator for all platform in java
public class FileSeparatorExample {
public static void main(String[] args) {
// The system property for key 'file.separator'
// get the correct file file separator for
// each different platform like Windows = \ and Linux = /
String fileSeparator = System.getProperty("file.separator");
// You can also use the File class constant File.separator
// to get the file separator for any platform.
String fileSeparator2 = File.separator;
System.out.println("The file separator for current platform is : "
+ fileSeparator);
System.out.println("The file separator for current platform is : "
+ fileSeparator2);
}
}

The output of the above example will be as in window operating system:

The file separator for current platform is : \
The file separator for current platform is : \