Junior — Middle
How are path separators implemented in different operating systems to ensure platform independence?
sobes.tech AI
Answer from AI
Path separators differ across operating systems:
- Windows uses the backslash
\. - Unix-like systems (Linux, macOS) use the forward slash
/.
To ensure platform independence in Java, the class java.nio.file.Path and methods from java.nio.file.Paths are used, or the constant File.separator, which contains the correct separator for the current OS.
Example:
import java.io.File;
String path = "folder" + File.separator + "file.txt";
Or using Path:
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("folder", "file.txt");
This approach allows writing code that works correctly on different platforms without manually specifying separators.