Here you can find the source of toBytes(CharSequence str, String charsetName)
Parameter | Description |
---|---|
str | the string to encode into bytes |
charsetName | the name of a supported java.nio.charset.Charset charset |
public static byte[] toBytes(CharSequence str, String charsetName)
//package com.java2s; /*//w ww. j a v a 2 s .com * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * * 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 * * http://www.apache.org/licenses/LICENSE-2.0 * * 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 { /** * Encodes the given string into a sequence of bytes using the named charset. * <p> * This is a convenience method which wraps the checked exception with a RuntimeException. * The exception can never occur given the charsets * US-ASCII, ISO-8859-1, UTF-8, UTF-16, UTF-16LE or UTF-16BE. * * @param str the string to encode into bytes * @param charsetName the name of a supported {@linkplain java.nio.charset.Charset charset} * @return the encoded bytes */ public static byte[] toBytes(CharSequence str, String charsetName) { try { return str.toString().getBytes(charsetName); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } /** * Constructs a new String by decoding the given bytes using the specified charset. * <p> * This is a convenience method which wraps the checked exception with a RuntimeException. * The exception can never occur given the charsets * US-ASCII, ISO-8859-1, UTF-8, UTF-16, UTF-16LE or UTF-16BE. * * @param bytes the bytes to be decoded into characters * @param charsetName the name of a supported {@linkplain java.nio.charset.Charset charset} * @return the decoded String */ public static String toString(byte[] bytes, String charsetName) { try { return new String(bytes, charsetName); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }