Here you can find the source of getMaxBytes(String string, int maxBytes, Charset charSet)
maxBytes
of string
encoded using the encoder of charSet
Parameter | Description |
---|---|
string | whose prefix bytes to return |
maxBytes | the maximum number of bytes to return |
charSet | the char set used for encoding the characters into bytes |
Parameter | Description |
---|---|
CharacterCodingException | if the char set's encoder could nothandle the characters in the string |
static byte[] getMaxBytes(String string, int maxBytes, Charset charSet) throws CharacterCodingException
//package com.java2s; /*//from w w w . j a v a2 s . c om * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * 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.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; public class Main { /** * Returns the first <code>maxBytes</code> of <code>string</code> encoded * using the encoder of <code>charSet</code> * @param string whose prefix bytes to return * @param maxBytes the maximum number of bytes to return * @param charSet the char set used for encoding the characters into bytes * @return the array of bytes of length <= maxBytes * @throws CharacterCodingException if the char set's encoder could not * handle the characters in the string */ static byte[] getMaxBytes(String string, int maxBytes, Charset charSet) throws CharacterCodingException { byte[] bytes = new byte[maxBytes]; ByteBuffer out = ByteBuffer.wrap(bytes); CharBuffer in = CharBuffer.wrap(string.toCharArray()); CharsetEncoder encoder = charSet.newEncoder(); CoderResult cr = encoder.encode(in, out, true); encoder.flush(out); if (cr.isError()) { cr.throwException(); } byte[] result = new byte[out.position()]; System.arraycopy(bytes, 0, result, 0, result.length); return result; } }