// Shortcut if there is no work to do if (pathToUse.indexOf('.') == -1) { return pathToUse; }
// Strip prefix from path to analyze, to not treat it as part of the // first path element. This is necessary to correctly parse paths like // "file:core/../core/io/Resource.class", where the ".." should just // strip the first "core" directory while keeping the "file:" prefix. //字符串分为前缀和内容 intprefixIndex= pathToUse.indexOf(':'); Stringprefix=""; if (prefixIndex != -1) { prefix = pathToUse.substring(0, prefixIndex + 1); //这是因为在后面的处理过程中,如果前缀不为空,会在处理过程中加上一个路径分隔符 FOLDER_SEPARATOR,从而使得最终结果的前缀和传入的前缀不一致。因此需要在处理之前将前缀置空,以避免这个问题。 if (prefix.contains(FOLDER_SEPARATOR)) { prefix = ""; } else { pathToUse = pathToUse.substring(prefixIndex + 1); } } if (pathToUse.startsWith(FOLDER_SEPARATOR)) { prefix = prefix + FOLDER_SEPARATOR; pathToUse = pathToUse.substring(1); } //一个字符串转数组的工具方法, 详细 待续,此处以 "/" 为分隔符 String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); // we never require more elements than pathArray and in the common case the same number Deque<String> pathElements = newArrayDeque<>(pathArray.length); // ".." 的数量 inttops=0;
for (inti= pathArray.length - 1; i >= 0; i--) { Stringelement= pathArray[i]; // CURRENT_PATH == "." if (CURRENT_PATH.equals(element)) { // Points to current directory - drop it. } //".." == TOP_PATH //..表示返回上一级路径 elseif (TOP_PATH.equals(element)) { // Registering top path found. tops++; } else { if (tops > 0) { // Merging path element with element corresponding to top path. tops--; } else { // Normal path element found. pathElements.addFirst(element); } } }
// All path elements stayed the same - shortcut if (pathArray.length == pathElements.size()) { return normalizedPath; } // Remaining top paths need to be retained. for (inti=0; i < tops; i++) { pathElements.addFirst(TOP_PATH); } // If nothing else left, at least explicitly point to current path.
intpos=0; // our position in the old string intpatLen= oldPattern.length(); while (index >= 0) { sb.append(inString, pos, index); sb.append(newPattern); pos = index + patLen; index = inString.indexOf(oldPattern, pos); }
// append any characters to the right of a match sb.append(inString, pos, inString.length()); return sb.toString(); }