[Java] How to use File.separator to specify delimiters according to the platform

Java
スポンサーリンク

About File Delimiters

When referencing a file from a specific path, are you specifying the file delimiter as a string? By the way, a file delimiter is a character used to separate paths and files when specifying a file path, such as “\”, “/”, “:”, and others.

For example like this.
I am not aware of the delimiters for each OS.

//Windows
String path = "AAA¥¥BBB¥¥java.txt";
//Linux
String path = "AAA/BBB/java.txt";
//Mac (I dont know..)

It seems that the way to specify delimiters differs depending on the platform.
Not knowing this, you might encounter situations where it works on one OS but not on another.
So, if we could determine the OS…

String os = System.getProperty("os.name");
if (os.indexOf("Windows") >= 0){
  // Windows
  String path = "AAA¥¥BBB¥¥java.txt";
} else if (os.indexOf("Linux") >= 0) {
  // Linux
  String path = "AAA/BBB/java.txt";
} else if(os.indexOf("Mac") >= 0){
  // MacOS
} else {
  // Others
}

Depending on the process, in this case, it’s quite redundant, isn’t it…

Use File.separator.

To conclude the solution, let’s use File.separator.
It automatically detects the correct delimiter based on the platform.

Just like this.

String path = "AAA" + File.separator + "BBB" + File.separator + "1.mht";

Since Java is a multi-platform language,
it’s important to consider the characteristics of each OS when implementing.

タイトルとURLをコピーしました