The ambiguous path separator on Windows - how to handle it?

Another question caused an interesting problem:

On Windows, Java File.pathSeparatorChar ; , it is right. However, the semicolon is also actually a valid character for folder or file names. You can create a folder called Test;Test1 on Windows.

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

+5
source share
3 answers

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

after a little PoC

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

the conclusion will be

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

means dummy.cmd found by setting the path.

to change . As can be seen from the comments: using a seven-clone can lead to some trouble. It is better to avoid using directory names containing a semicolon.

+3
source

Since the question is for Java and based on @SubOptimal answer , which explains that paths with a semicolon should be enclosed in quotation marks, here is a small example of code for extracting paths from such a list, separated by the File.pathSeparator symbol:

 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, a regular expression without escape characters (?:(?:"([^"]*)")|([^;]+));? .

+1
source

On 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 PATH . To find the short name, use DIR /X For instance:

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

All Articles