集册 Java实例教程 从给定的内容返回字符集

从给定的内容返回字符集

欢马劈雪     最近更新时间:2020-01-02 10:19:05

502
从给定的内容类型返回字符集。
/**nowjava.com**/

/******************************************************************************* 

 * Copyright (c) 2008 Red Hat, Inc. 

 * Distributed under license by Red Hat, Inc. All rights reserved. 

 * This program is made available under the terms of the 

 * Eclipse Public License v1.0 which accompanies this distribution, 

 * and is available at http://www.eclipse.org/legal/epl-v10.html 

 * 

 * Contributors: 

 * Xavier Coulon - Initial API and implementation 

 ******************************************************************************/

//package com.nowjava;

import java.nio.charset.Charset;

import java.nio.charset.UnsupportedCharsetException;

import java.util.StringTokenizer;


public class Main {

    /**

     * Returns the {@link Charset} from the given content-type.

     * 

     * @param contentType

     *            the given content type that may contain some ";charset=...".

     * @param defaultCharsetName

     *            the name of the default charset to return in case when the given

     *            contentType would be null or would not contain any specific

     *            charset. If this name cannot be resolved into a valid charset, then "UTF-8" is used.

     * @return the value of the "charset" token in the given contentType, or

     *         the given defaultCharsetName, or "UTF-8" as a last resort.

     */

    public static Charset getContentCharSet(final String contentType,

            final String defaultCharsetName) {

        if (contentType != null) {

            final StringTokenizer stk = new StringTokenizer(contentType,

                    ";");

            while (stk.hasMoreTokens()) {//from NowJava.com

                final String token = stk.nextToken().toLowerCase()

                        .replace(" ", "");

                if (token.startsWith("charset=")) {

                    final StringTokenizer tokenSplitter = new StringTokenizer(

                            token, "=");

                    tokenSplitter.nextToken(); // skip the 'charset' part as we already know it

                    final String value = tokenSplitter.hasMoreTokens() ? tokenSplitter

     
展开阅读全文