Java String convert byte array to String using Latin-1/ISO-8859-1 encoding

Description

Java String convert byte array to String using Latin-1/ISO-8859-1 encoding


//package com.demo2s;

import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] argv) throws Exception {
        byte[] ba = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(bytesToLatin1(ba));
    }/* w w w  .  j  a  v a2  s  .  com*/

    /**
     * Convert a byte array to a String using Latin-1 (aka ISO-8859-1) encoding.
     *
     * Note: something is probably wrong if you're using this method. Either
     *       you're dealing with legacy code that doesn't support i18n or you're
     *       using a third-party library that only deals with Latin-1. New code
     *       should (almost) always uses UTF-8 encoding.
     *
     * @return the decoded String or null if ba is null
     */
    public static String bytesToLatin1(final byte[] ba) {
        // ISO-8859-1 should always be supported
        return bytesToEncoding(ba, "ISO-8859-1");
    }

    /**
     * Convert a byte array to a String using the specified encoding.
     * @param encoding the encoding to use
     * @return the decoded String or null if ba is null
     */
    private static String bytesToEncoding(final byte[] ba, final String encoding) {
        if (ba == null) {
            return null;
        }

        try {
            return new String(ba, encoding);
        } catch (final UnsupportedEncodingException e) {
            throw new Error(encoding + " not supported! Original exception: " + e);
        }
    }
}



PreviousNext

Related