Java tutorial
//package com.java2s; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CodingErrorAction; public class Main { /** * List of Japanese encodings to convert text for data importing. * These encodings are tries in the order, in other words, UTF-8 is the most high-prioritized * encoding. */ private static final String[] JAPANESE_ENCODING_LIST = { "UTF-8", "EUC-JP", "ISO-2022-JP", "Shift_JIS", "UTF-16", }; /** * Returns the {@code String} instance with detecting the Japanese encoding. * @throws UnsupportedEncodingException if it fails to detect the encoding. */ static String toStringWithEncodingDetection(ByteBuffer buffer) throws UnsupportedEncodingException { for (String encoding : JAPANESE_ENCODING_LIST) { buffer.position(0); try { Charset charset = Charset.forName(encoding); CharBuffer result = charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT) .onUnmappableCharacter(CodingErrorAction.REPORT).decode(buffer); String str = result.toString(); if (str.length() > 0 && str.charAt(0) == 0xFEFF) { // Remove leading BOM if necessary. str = str.substring(1); } return str; } catch (Exception e) { // Ignore exceptions, and retry next encoding. } } throw new UnsupportedEncodingException("Failed to detect encoding"); } }