Retrieves a UTF-8 byte representation of the provided string. - Java java.lang

Java examples for java.lang:String UTF

Description

Retrieves a UTF-8 byte representation of the provided string.

Demo Code

/*/*from   w ww  .  j  a  v  a 2s.  c o m*/
 * Copyright 2011-2016 UnboundID Corp.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License (GPLv2 only)
 * or the terms of the GNU Lesser General Public License (LGPLv2.1 only)
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses>.
 */
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main{
    /**
     * Retrieves a UTF-8 byte representation of the provided string.
     *
     * @param  s  The string for which to retrieve the UTF-8 byte representation.
     *
     * @return  The UTF-8 byte representation for the provided string.
     */
    public static byte[] getUTF8Bytes(final String s) {
        final int length;
        if ((s == null) || ((length = s.length()) == 0)) {
            return new byte[0];
        }

        final byte[] b = new byte[length];
        for (int i = 0; i < length; i++) {
            final char c = s.charAt(i);
            if (c <= 0x7F) {
                b[i] = (byte) (c & 0x7F);
            } else {
                try {
                    return s.getBytes("UTF-8");
                } catch (Exception e) {
                    // This should never happen.
                    Debug.debugException(e);
                    return s.getBytes();
                }
            }
        }
        return b;
    }
}

Related Tutorials