Check if path is valid or legal in java

Possible duplicate:
Is there a way in Java to determine if a path is valid without trying to create a file?

I want to check if a string is a valid path name for a folder or file. Valid path names may be C: \ Games \ WarCraft, and the invalid path may be c: [] [] Games \\ WarCraft. How to check if this is correct?

I am NOT interested in checking for a file or folder. I don't want to use any external libraries like Apache Commons, just old java.

In addition, I want my code system to be independent - UPDATE , which is not needed, although

Tips, please! :)

+2
java
Dec 18
source share
1 answer

You cannot do this in a system-independent way, and I don't think there are standard APIs for checking the path name.

The best suggestion I can come up with is to use a regular expression to match the path name. The exact details will depend on how loose or tight you want to limit the path. For example, on Linux, you can disable spaces in path names, because although they are valid, they also cause problems for poorly written shell scripts. Or you can insist on absolute (or relative) tracks.

But before you run the regex, it would be nice to canonize the path with File.getCanonicalFile() . This will do things like checking for symbolic links, getting rid of redundant ". And" .. "s, and turning drive letters into standard form ... that should simplify your regular expression.

+2
Dec 18 '12 at 1:11
source share



All Articles