Calculates the byte length of a UTF-8 encoded string. - Java java.lang

Java examples for java.lang:String UTF

Description

Calculates the byte length of a UTF-8 encoded string.

Demo Code

/**/*from  w  w  w.  j  av a2 s .com*/
 * Copyright 2013-2014 Amazon.com, 
 * Inc. or its affiliates. All Rights Reserved.
 * 
 * Licensed under the Amazon Software License (the "License"). 
 * You may not use this file except in compliance with the 
 * License. A copy of the License is located at
 * 
 *     http://aws.amazon.com/asl/
 * 
 * or in the "license" file accompanying this file. This file is 
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
 * CONDITIONS OF ANY KIND, express or implied. See the License 
 * for the specific language governing permissions and 
 * limitations under the License.
 */
//package com.java2s;
import java.nio.charset.Charset;

public class Main {
    /**
     * UTF-8 {@link Charset}
     */
    private static final Charset UTF_8 = Charset.forName("UTF-8");

    /**
     * Calculates the byte length of a UTF-8 encoded string. 0 if the string is
     * null.
     * 
     * @param string string to be computed
     * @return byte length of a UTF-8 string in bytes, 0 if null.
     */
    public static long utf8ByteLength(String string) {
        if (string == null) {
            return 0;
        }
        return string.getBytes(UTF_8).length;
    }
}

Related Tutorials