Java Byte Array to String by Charset getNumberOfBytesPerCharacter(final String charsetName)

Here you can find the source of getNumberOfBytesPerCharacter(final String charsetName)

Description

Returns the number of bytes per character in the given charset.

License

Apache License

Parameter

Parameter Description
charsetName a charset name.

Return

the number of fixed-width bytes per character in the charset or -1 if charset is variable-width.

Declaration

public static int getNumberOfBytesPerCharacter(final String charsetName) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;

public class Main {
    /**/*  w ww.  jav a2  s .c om*/
     * Returns the number of bytes per character in the given charset.
     * 
     * @param charsetName a charset name.
     * @return the number of fixed-width bytes per character in the charset or -1 if charset is variable-width.
     */
    public static int getNumberOfBytesPerCharacter(final String charsetName) {
        if (!isFixedWith(charsetName)) {
            return -1;
        }

        final Charset charset = Charset.forName(charsetName);
        final CharsetEncoder encoder = charset.newEncoder();
        return (int) encoder.maxBytesPerChar();
    }

    /**
     * Returns whether the given charset is fixed-width.
     * 
     * @param charsetName a charset name.
     * @return true if the charset is fixed-width, false if the charset is variable-width.
     */
    public static boolean isFixedWith(final String charsetName) {
        checkNotNull(charsetName, "Argument charsetName must not be null.");
        checkArgument(Charset.isSupported(charsetName), "Charset '%s' is not supported.", charsetName);

        final Charset charset = Charset.forName(charsetName);
        final CharsetEncoder encoder = charset.newEncoder();
        return encoder.averageBytesPerChar() == encoder.maxBytesPerChar();
    }
}

Related

  1. getBytesUnchecked(String string, String charsetName)
  2. getBytesUnchecked(String string, String charsetName)
  3. getChars(byte[] data, String charset)
  4. getContentAsString(byte[] content, Charset charset)
  5. getMaxBytes(String string, int maxBytes, Charset charSet)
  6. getPrefixWithMaxBytes(String string, int maxBytes, Charset charSet)
  7. getRowId(final byte[] rowId, final Charset charset, final boolean base64encodeValues)
  8. getString(@Nonnull byte[] b, @Nonnegative int bufferSize, @Nonnegative int offset, @Nonnull Charset charset)
  9. getString(byte[] bytes, String charset)