Question

I am using Windows 7. Here is my code:

public class DriveLettersList {
    public static void main( String[] args ) {
        System.setProperty( "file.separator", "/" );

        System.out.println( System.getProperty( "file.separator" ) );
        System.out.println( Paths.get( "hello", "my", "word" ) );
}

The output was confusing:

/
hello\my\word

Why Paths.get returns the default path separator for Windows ?

Was it helpful?

Solution

Notice the javadoc of Paths.get(..)

The details as to how the Strings are joined is provider specific but typically they will be joined using the name-separator as the separator.

where the name separator can be retrieved with

FileSystems.getDefault().getSeparator()

Where, on Windows with WindowsFileSystem, it is implemented as

@Override
public String getSeparator() {
    return "\\";
}

With this FileSystem implementation, you can't change it.

This might be different on Unix systems. Actually, it seems it isn't

public final String getSeparator() {
    return "/";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top