Tuesday, 7 October 2014

Encoding to unicode

A code example which encodes a String into UTF-16L.
  
   /**
    * Utility method to convert a String to UTF-16LE.
    *
    * @param stringToConvert
    */
   public String encodeToUtf16Le(String stringToConvert) {
      String stringToReturn = null;
      Charset charset = Charset.forName("UTF-16LE");
      CharsetDecoder decoder = charset.newDecoder();
      CharsetEncoder encoder = charset.newEncoder();

      try {
         // Convert a string to UTF-16LE bytes in a ByteBuffer
         // The new ByteBuffer is ready to be read.
         ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(" "+stringToConvert)).put(0, (byte) 0xFF).put(1,
               (byte) 0xFE);

         // Convert UTF-16LE bytes in a ByteBuffer to a character ByteBuffer and then to a string.
         // The new ByteBuffer is ready to be read.
         CharBuffer cbuf = decoder.decode(bbuf);
         stringToReturn = cbuf.toString();

      } catch (CharacterCodingException ex) {
         LOG.error("An exception happened while converting a string to UTF-16LE. Given string to convert: '"
               + stringToConvert + "'", ex);
      }

      return stringToReturn;
   }