Java UTF8 From getUTF8Bytes(String s)

Here you can find the source of getUTF8Bytes(String s)

Description

Convert a String into a byte[] encoded by UTF-8.

License

Apache License

Parameter

Parameter Description
s string to encode into bytes

Declaration

public static byte[] getUTF8Bytes(String s) 

Method Source Code

//package com.java2s;
/**/*from   w ww  .j  av a2s  . c om*/
 * Useful String utilities for common tasks
 *
 * @author Ken Partlow
 * @author John DeRegnaucourt (john@cedarsoftware.com)
 *         <br>
 *         Copyright (c) Cedar Software LLC
 *         <br><br>
 *         Licensed 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
 *         <br><br>
 *         http://www.apache.org/licenses/LICENSE-2.0
 *         <br><br>
 *         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.UnsupportedEncodingException;

public class Main {
    /**
     * Convert a String into a byte[] encoded by UTF-8.
     *
     * @param s        string to encode into bytes
     */
    public static byte[] getUTF8Bytes(String s) {
        return getBytes(s, "UTF-8");
    }

    /**
     * Convert a String into a byte[] with a particular encoding.
     * Preferable used when the encoding is one of the guaranteed Java types
     * and you don't want to have to catch the UnsupportedEncodingException
     * required by Java
     *
     * @param s        string to encode into bytes
     * @param encoding encoding to use
     */
    public static byte[] getBytes(String s, String encoding) {
        try {
            return s == null ? null : s.getBytes(encoding);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(
                    String.format("Encoding (%s) is not supported by your JVM", encoding), e);
        }
    }
}

Related

  1. getUTF8(String s)
  2. getUTF8(String string)
  3. getUTF8Bytes(String data)
  4. getUtf8Bytes(String s)
  5. getUTF8Bytes(String s)
  6. getUtf8Bytes(String s)
  7. getUTF8Bytes(String str)
  8. getUtf8Bytes(String str)
  9. getUtf8Bytes(String str)