BRHSM
BRHSM

Reputation: 884

check if a string is a theoretical filepath/directory in java

I'm working on a program for which I need to see if a string could theoretically be a filepath/directory (ether absolute or relative). I've been looking around trying to see if there is an easy way to do this and I'm finding loads of questions which focus on also seeing if the file/folder exists (e.g., this or this)

Is there a way to see if a string is a filepath/directory without it actually having to exists?

EDIT: I was asked in the comments to elaborate on what a valid filepath/directory is:

The way my program handles filepaths is that it usually (depending on exactly what it needs to load) takes a few "parts" of the filepath/directory and uses that to read a file.

Therefore we can use the following rules:

either the string contains a filepath which:

Directories, however

Also, no spaces are allowed in the string.

I'm making the software to run on Windows initially but I might need to port it to Linux (therefore changing the name of the root folder and maybe more).

Upvotes: 2

Views: 2816

Answers (1)

Khurram
Khurram

Reputation: 181

You can use Paths.get() to determine if a path is valid or not.

try {
    Paths.get(path);
} catch (InvalidPathException | NullPointerException ex) {
    return false;
}
return true;

For checking a semantically valid absolute path, you can use File.isAbsolute().

EDIT: Based on your requirement of not allowing spaces, you will need to check that separately. Windows allows spaces to be part of file names.

Upvotes: 2

Related Questions