Ambiguous path separator on Windows - how to handle it?

别说谁变了你拦得住时间么 提交于 2019-12-23 10:35:06

问题


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?


回答1:


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.




回答2:


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 (?:(?:"([^"]*)")|([^;]+));?.




回答3:


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%


来源:https://stackoverflow.com/questions/29623826/ambiguous-path-separator-on-windows-how-to-handle-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!