Nederealm
Nederealm

Reputation: 447

Get file.separator of a specified file path

How do you get a file separator of a specified file/folder path?

In Java, we can write, for example

File f = new File("C:\\MyFolder\\MyText.txt");

Keep in mind this is a file representation (the file does not have to exist physically). So given any specified path, is there a method that can return the separator for that specified path only?

From the docs

The File.pathSeparator and File.pathSeparatorChar returns system dependent file separator, but what I want is the separator for a given path, like in the above case \, even if the above program is run and the path is not valid for *nix

Upvotes: 0

Views: 992

Answers (2)

The separator character for File objects is always given by File.separator (or File.separatorChar). There is no way to construct a File object with an unusual separator; they always hold paths that are valid on the current system.

File f = new File("C:\\MyFolder\\MyText.txt");

After executing this line on Windows, f refers to a File object that refers to the file MyText.txt in the folder MyFolder on drive C:, as you probably intended.

But on Linux, f refers to a File object that refers to the file C:\MyFolder\MyText.txt in the current directory. (On Linux, backslashes are allowed in filenames)

Imagine if there was a way to do this. If you had a File constructed with new File("a/b\\c"), then how would you know whether it was referring to the file b\c in the folder a (with separator /), or the file c in the folder a/b (with separator \)?

It can't, so it should be clear that there is no reliable way to do this. If your program handles paths with unusual separators, then your program needs to handle them itself. File cannot do it for you.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

I would start with System.getProperty("user.home"). And, you could use File.seperator like

File f = new File(System.getProperty("user.home") + 
        File.seperator + "MyText.txt");

but I would prefer File(String parent, String child) like

File f = new File(System.getProperty("user.home"), "MyText.txt");
System.out.println(f.getPath());

Upvotes: 1

Related Questions