Platform independent paths in Java

Viewed 109440

I know the relative path of a file and want to handle it as a File object on both Linux and Windows.

What is the best way to specify platform-independent paths in Java?

8 Answers

Only 10 years too late.... The "It doesn't matter just use '/'" is only half true (ok, three quarters). You have to think about where your data is coming from.

If you get a path in Java, it will use '/' If you create a path in Java it will understand '/'

But what about paths that are input to your program?

Suppose I have a series of scripts that create a config (Properties) file. Suppose one of the config variables is INTERESTING_FILE, and we generate this to be a filename including path. Now suppose I want to extract the actual Filename from that, so I say

String[] filename = INTERESTING_FILE.split("/");

This will misbehave on Windows Systems, however

String[] filename = INTERESTING_FILE.split(pathSeparator);

will work (as will washing it through the Paths class).

I guess the point is, I wouldn't assume '/' is going to work in every case.

Related