Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Ambiguous path separator on Windows - how to handle it?

Another question brought up an interesting problem:

On Windows, the Java File.pathSeparatorChar is ;, which is correct. However, the semicolon is actually also a valid character to folder or file names. You can create a folder named Test;Test1 on Windows.

The question is: How would you determine whether the semicolon in a path list actually separates a path or is part of the directory name, if the path list can contain both absolute and relative paths?

Upvotes: 6

Views: 676

Answers (3)

SubOptimal
SubOptimal

Reputation: 22973

If the path contains a ; itself the path must be surrounded by double quotes ".

following small PoC

mkdir "foo;bar"
echo echo execute %%~dpnx0 > "foo;bar\dummy.cmd"
set PATH=%PATH%;"foo;bar"
dummy.cmd

the output will be

execute R:\temp\foo;bar\dummy.cmd

means the dummy.cmd is found by the path setup.

edit As to see from the comments: Using a semiclon could lead you into some trouble. It's better to avoid using directory names containing a semicolon.

Upvotes: 5

Métoule
Métoule

Reputation: 14472

Since the question is for Java, and based on @SubOptimal answer that explains that paths with a semicolon should be enclosed in quotes, here's a small code sample to extract paths from such a list separated by File.pathSeparator:

String separatedList  = "\"test;test1\";c:\\windows;\"test2\";test3;;test4";

String pattern = String.format("(?:(?:\"([^\"]*)\")|([^%1$s]+))%1$s?", File.pathSeparator);
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(separatedList);
while (m.find())
{
    for (int i = 1; i <= m.groupCount(); i++)
    {
        String path = m.group(i);
        if (path != null)
            System.out.println(path);
    }
}

For reference, the regex without the escaping characters is (?:(?:"([^"]*)")|([^;]+));?.

Upvotes: 1

Always Learning
Always Learning

Reputation: 5581

In a Windows PATH the semicolon is always a separator. If you have a folder with a semicolon in the name, you can put its short alternate name in the PATH. To find the short name use DIR /X. For example:

C:\> dir test* /X
<DIR>   **TEST_T~1**     Test;Test1
C:\> set PATH=TEST_T~1;%PATH%

Upvotes: 0

Related Questions