Java Byte Array from getBytes(final String data, String charset)

Here you can find the source of getBytes(final String data, String charset)

Description

Converts the specified string to a byte array.

License

Open Source License

Parameter

Parameter Description
data the string to be encoded
charset the desired character encoding

Return

The resulting byte array.

Declaration

public static byte[] getBytes(final String data, String charset) 

Method Source Code


//package com.java2s;

import java.io.UnsupportedEncodingException;

public class Main {
    /**//from   w w  w.j a  va2 s . c o  m
     * Converts the specified string to a byte array.  If the charset is not 
     * supported the default system charset is used.
     *
     * @param data the string to be encoded
     * @param charset the desired character encoding
     * @return The resulting byte array.
     */
    public static byte[] getBytes(final String data, String charset) {

        if (data == null) {
            throw new IllegalArgumentException("data may not be null");
        }

        if (charset == null || charset.length() == 0) {
            throw new IllegalArgumentException("charset may not be null or empty");
        }

        try {
            return data.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            return data.getBytes();
        }
    }
}

Related

  1. getBytes(Class clazz)
  2. getBytes(Class clazz)
  3. getBytes(Class cls, String resourceName)
  4. getBytes(final InputStream is)
  5. getBytes(final Serializable obj)
  6. getBytes(final String data, String charset)
  7. getBytes(final String value, final String characterEncoding)
  8. getBytes(int length, InputStream inStream)
  9. getBytes(int value)