Here you can find the source of normalize(String absoluteURL)
Parameter | Description |
---|---|
absoluteURL | the absolute URI to normalize |
public static String normalize(String absoluteURL) throws MalformedURLException
//package com.java2s; import java.net.MalformedURLException; import java.util.Stack; import java.util.StringTokenizer; public class Main { /**/*from w w w. j a v a2 s . c om*/ * the path separator for an URI */ private static final char HREF_PATH_SEP = '/'; /** * the path separate for a URL as a String */ private static final String URL_PATH_SEP_STR = "/"; /** * The current directory designator */ private static final String CURRENT_DIR_OP = "."; /** * The parent directory designator */ private static final String PARENT_DIR_OP = ".."; /** * This method removes "." or ".." from absolute URL. * I needed this method because the JDK doesn't do this * automatically when creating URLs. * * @param absoluteURL the absolute URI to normalize */ public static String normalize(String absoluteURL) throws MalformedURLException { if (absoluteURL == null) { return absoluteURL; } if (absoluteURL.indexOf('.') < 0) { return absoluteURL; } //-- Note: using StringTokenizer and Stacks //-- is not very efficient, this may need //-- some optimizing Stack tokens = new Stack(); StringTokenizer st = new StringTokenizer(absoluteURL, URL_PATH_SEP_STR, true); String last = null; while (st.hasMoreTokens()) { String token = st.nextToken(); if (URL_PATH_SEP_STR.equals(token)) { if (URL_PATH_SEP_STR.equals(last)) { tokens.push(""); } } else if (PARENT_DIR_OP.equals(token)) { if (tokens.empty()) { //-- this should be an error throw new MalformedURLException( "invalid absolute URL: " + absoluteURL); } tokens.pop(); } else { if (!CURRENT_DIR_OP.equals(token)) { tokens.push(token); } } last = token; } //-- rebuild URL StringBuffer buffer = new StringBuffer(absoluteURL.length()); for (int i = 0; i < tokens.size(); i++) { if (i > 0) { buffer.append(HREF_PATH_SEP); } buffer.append(tokens.elementAt(i).toString()); } return buffer.toString(); } }