2

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.

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
John Freeman
  • 2,552
  • 1
  • 27
  • 34
  • forward slash is an alternate separator on MS Windows but not, for example, on Mac OS 9. – Random832 Mar 27 '15 at 18:50
  • @aioobe if I remember correctly, forward slash can be a normal part of a filename on OS 9. So you could have a file called "Meeting Notes 12/5/2000". Of course, OS 9 isn't exactly a major platform anymore. But it's part of the reasoning behind the feature. In OSX, with its unix-based filesystem, it will internally store it as a colon in the filename. – Random832 Mar 27 '15 at 19:05

3 Answers3

3

/ 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"));
Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • So the shortest way is `path.resolve(path.getFileSystem().getPath("foo", "bar", "baz"))`? – John Freeman Mar 27 '15 at 20:51
  • Is `foo` the root directory, or do you have a path `root` and want to construct `root/foo/bar/baz`? – aioobe Mar 27 '15 at 21:15
  • The second. Have a path, want to compute something relative in the most concise possible way. In my opinion, there should be a `resolve` method that takes an array of strings, but alas, we do not have that. – John Freeman Mar 27 '15 at 21:21
1

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

You can do first FileSystem.getPath("foo", "bar", "baz") to get Path and instead of sending String to Path.resolve() you can use overloaded one which accepts Path.

Nenad Bozic
  • 3,724
  • 19
  • 45