Java String Decode decode(String s, String encoding)

Here you can find the source of decode(String s, String encoding)

Description

decode

License

Apache License

Declaration

public static String decode(String s, String encoding)
            throws UnsupportedEncodingException 

Method Source Code

//package com.java2s;
/**//from  ww w.  j  ava2s. c  o  m
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.ByteArrayOutputStream;
import java.io.UnsupportedEncodingException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern ENCODED_VALUE_PATTERN = Pattern.compile(
            "%[0-9a-f]{2}|\\S", Pattern.CASE_INSENSITIVE);

    public static String decode(String s, String encoding)
            throws UnsupportedEncodingException {
        Matcher matcher = ENCODED_VALUE_PATTERN.matcher(s);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while (matcher.find()) {
            String matched = matcher.group();
            if (matched.startsWith("%")) {
                Integer value = Integer.parseInt(matched.substring(1), 16);
                bos.write(value);
            } else {
                bos.write(matched.charAt(0));
            }
        }

        return new String(bos.toByteArray(), encoding);
    }
}

Related

  1. decode(String s)
  2. decode(String s)
  3. decode(String s, Class clazz)
  4. decode(String s, String charset1, String charset2)
  5. decode(String s, String enc, boolean plusToSpace)
  6. decode(String str)
  7. decode(String str)
  8. decode(String str, String encoding)
  9. decode(String string, String encoding)