Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will forward slash work across platforms in Path.resolve?

Tags:

java

path

Since Path.resolve does not accept an array of strings, it is possible pass a relative path containing multiple path components, e.g. "foo/bar/baz".

My question is

if the forward slash in such a relative path will work as intended across platforms?

I have seen some answers on here that allege Java treats forward slashes as a "universal separator", but not citations to support them.

like image 467
John Freeman Avatar asked Nov 16 '25 02:11

John Freeman


2 Answers

/ should be a valid path separator on all major platforms of today. See for instance File.separator vs Slash in Paths (maybe it's even a dup?)

If you're the pedantic type you can use FileSystem.getSeparator.

Note that you can also do

root.resolve(Paths.get("foo", "bar", "baz"));
like image 87
aioobe Avatar answered Nov 17 '25 17:11

aioobe


No. The typical / in Path objects is called a name separator. It is defined in the FileSystem object from which the Path was created.

You can retrieve it with FileSystem#getSeparator().

Returns the name separator, represented as a string.

The name separator is used to separate names in a path string. An implementation may support multiple name separators in which case this method returns an implementation specific default name separator. This separator is used when creating path strings by invoking the toString() method.

In the case of the default provider, this method returns the same separator as java.io.File.separator.

You can retrieve a Path's FileSystem with Path#getFileSystem().

As far as I know, all typical file systems will use / as a separator, but you could write your own FileSystem implementation which doesn't.

like image 33
Sotirios Delimanolis Avatar answered Nov 17 '25 18:11

Sotirios Delimanolis