Java Path Encode encodePath(String url)

Here you can find the source of encodePath(String url)

Description

URL encodes the path.

License

Open Source License

Parameter

Parameter Description
path the path to encode

Return

the encoded path

Declaration

public static String encodePath(String url) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;

import java.util.Locale;
import java.util.StringTokenizer;

public class Main {
    /**/*www . j a  va  2s .c  o  m*/
     * URL encodes the path.
     *
     * @param path the path to encode
     * @return the encoded path
     */
    public static String encodePath(String url) {
        StringBuilder strbuf = new StringBuilder();
        String sub = url;
        String result = null;
        if (sub != null) {
            if (sub.startsWith("file://")) {
                sub = sub.substring("file://".length());
            }
            StringTokenizer strtok = new StringTokenizer(sub, "/");
            while (strtok.hasMoreTokens()) {
                String tok = strtok.nextToken();
                strbuf.append('/');
                strbuf.append(encodeURLComponent(tok));
            }
            result = strbuf.toString();
            if (!url.equals(sub)) {
                result = "file://" + result;
            }
        }
        return result;
    }

    public static String encodeURLComponent(final String s) {
        if (s == null) {
            return "";
        }

        final StringBuilder sb = new StringBuilder();

        try {
            for (int i = 0; i < s.length(); i++) {
                final char c = s.charAt(i);

                if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) || ((c >= '0') && (c <= '9'))
                        || (c == '-') || (c == '.') || (c == '_') || (c == '~')) {
                    sb.append(c);
                } else {
                    final byte[] bytes = ("" + c).getBytes("UTF-8");

                    for (byte b : bytes) {
                        sb.append('%');

                        int upper = (((int) b) >> 4) & 0xf;
                        sb.append(Integer.toHexString(upper).toUpperCase(Locale.US));

                        int lower = ((int) b) & 0xf;
                        sb.append(Integer.toHexString(lower).toUpperCase(Locale.US));
                    }
                }
            }

            return sb.toString();
        } catch (UnsupportedEncodingException uee) {
            throw new RuntimeException("UTF-8 unsupported!?", uee);
        }
    }
}

Related

  1. encodePath(String path)
  2. encodePath(String path)
  3. encodePath(String path)
  4. encodePath(String path, boolean encodeSlash, String charset)
  5. encodePathSegment(final String pathSegment)