Java Code Examples for java.nio.charset.Charset#decode()

The following examples show how to use java.nio.charset.Charset#decode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebsocketOutputStream.java    From TrackRay with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void write(byte[] buf, int off, int len) {
    if (webSocketSession!=null) {
        try {
            Charset cs = Charset.forName("UTF-8");
            ByteBuffer bb = ByteBuffer.allocate(buf.length);
            bb.put(buf);
            bb.flip();
            CharBuffer cb = cs.decode(bb);
            char[] array = cb.array();
            StringBuffer buffer = new StringBuffer();
            buffer.append(array, off, len);
            TextMessage textMessage = new TextMessage(buffer.toString());
            webSocketSession.sendMessage(textMessage);
        } catch (IOException e) {
            BinaryMessage binaryMessage = new BinaryMessage(buf, off, len, false);
            try {
                webSocketSession.sendMessage(binaryMessage);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
 
Example 2
Source File: Utils.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
    * Converts an input file stream into a char sequence.
    *
    * @throws IOException
    */
   static CharBuffer getCharSequence(final FileInputStream stream, Charset encoding) throws IOException {
       FileChannel channel = stream.getChannel();
       ByteBuffer bbuf = ByteBuffer.allocate((int) channel.size());
       try {
           channel.read(bbuf, 0);
       } catch (ClosedByInterruptException cbie) {
           return null;        //this is actually okay
       } finally {
           channel.close();
       }
       bbuf.rewind();
       CharBuffer cbuf = encoding.decode(bbuf);

       return cbuf;
}
 
Example 3
Source File: String.java    From juniversal with MIT License 6 votes vote down vote up
/**
 * Converts the byte array to a string using the default encoding as
 * specified by the file.encoding system property. If the system property is
 * not defined, the default encoding is ISO8859_1 (ISO-Latin-1). If 8859-1
 * is not available, an ASCII encoding is used.
 * 
 * @param data
 *            the byte array to convert to a string.
 * @param start
 *            the starting offset in the byte array.
 * @param length
 *            the number of bytes to convert.
 * @throws NullPointerException
 *             when {@code data} is {@code null}.
 * @throws IndexOutOfBoundsException
 *             if {@code length < 0, start < 0} or {@code start + length >
 *             data.length}.
 */
public String(byte[] data, int start, int length) {
    // start + length could overflow, start/length maybe MaxInt
    if (start >= 0 && 0 <= length && length <= data.length - start) {
        offset = 0;
        Charset charset = defaultCharset();
        int result;
        CharBuffer cb = charset
                .decode(ByteBuffer.wrap(data, start, length));
        if ((result = cb.length()) > 0) {
            value = cb.array();
            count = result;
        } else {
            count = 0;
            value = new char[0];
        }
    } else {
        throw new StringIndexOutOfBoundsException();
    }
}
 
Example 4
Source File: StrUtils.java    From jphp with Apache License 2.0 6 votes vote down vote up
@FastMethod
@Signature({
        @Arg("string"),
        @Arg("charset")
})
public static Memory decode(Environment env, Memory... args) {
    Charset charset;

    try {
        charset = Charset.forName(args[1].toString());
    } catch (Exception e) {
        return Memory.FALSE;
    }

    CharBuffer charBuffer = charset.decode(ByteBuffer.wrap(args[0].getBinaryBytes(env.getDefaultCharset())));
    return StringMemory.valueOf(charBuffer.toString());
}
 
Example 5
Source File: String.java    From juniversal with MIT License 5 votes vote down vote up
/**
 * Converts the byte array to a string using the specified encoding.
 * 
 * @param data
 *            the byte array to convert to a string.
 * @param start
 *            the starting offset in the byte array.
 * @param length
 *            the number of bytes to convert.
 * @param encoding
 *            the encoding.
 * @throws NullPointerException
 *             when {@code data} is {@code null}.
 * @throws IndexOutOfBoundsException
 *             if {@code length < 0, start < 0} or {@code start + length >
 *             data.length}.
 * @throws UnsupportedEncodingException
 *             if {@code encoding} is not supported.
 */
public String(byte[] data, int start, int length, final String encoding)
        throws UnsupportedEncodingException {
    if (encoding == null) {
        throw new NullPointerException();
    }
    // start + length could overflow, start/length maybe MaxInt
    if (start >= 0 && 0 <= length && length <= data.length - start) {
        offset = 0;
        Charset charset = getCharset(encoding);

        int result;
    	CharBuffer cb;
        try {
        	cb = charset.decode(ByteBuffer.wrap(data, start, length));
        } catch (Exception e) {
        	// do nothing. according to spec: 
        	// behavior is unspecified for invalid array
        	cb = CharBuffer.wrap("\u003f".toCharArray()); //$NON-NLS-1$
        }
        if ((result = cb.length()) > 0) {
            value = cb.array();
            count = result;
        } else {
            count = 0;
            value = new char[0];
        }
    } else {
        throw new StringIndexOutOfBoundsException();
    }
}
 
Example 6
Source File: StringDecoder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public String decode(DataBuffer dataBuffer, ResolvableType elementType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	Charset charset = getCharset(mimeType);
	CharBuffer charBuffer = charset.decode(dataBuffer.asByteBuffer());
	DataBufferUtils.release(dataBuffer);
	String value = charBuffer.toString();
	LogFormatUtils.traceDebug(logger, traceOn -> {
		String formatted = LogFormatUtils.formatValue(value, !traceOn);
		return Hints.getLogPrefix(hints) + "Decoded " + formatted;
	});
	return value;
}
 
Example 7
Source File: PluginDataOutputStream.java    From TrackRay with GNU General Public License v3.0 5 votes vote down vote up
public void write(byte[] buf, int off, int len) {
    Charset cs = Charset.forName("UTF-8");
    ByteBuffer bb = ByteBuffer.allocate(buf.length);
    bb.put(buf);
    bb.flip();
    CharBuffer cb = cs.decode(bb);
    char[] array = cb.array();
    StringBuffer buffer = new StringBuffer();
    buffer.append(array, off, len);
    stringBuffer.append(array,off,len);

}
 
Example 8
Source File: Utils.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
static char[] getChars(byte[] bytes) {
    Charset cs = Charset.forName("UTF-8");
    ByteBuffer bb = ByteBuffer.allocate(bytes.length);
    bb.put(bytes);
    bb.flip();
    CharBuffer cb = cs.decode(bb);

    return cb.array();
}
 
Example 9
Source File: Hex.java    From alpha-wallet-android with MIT License 5 votes vote down vote up
public static String hexToUtf8(String hex) {
    hex = org.web3j.utils.Numeric.cleanHexPrefix(hex);
    ByteBuffer buff = ByteBuffer.allocate(hex.length() / 2);
    for (int i = 0; i < hex.length(); i += 2) {
        buff.put((byte) Integer.parseInt(hex.substring(i, i + 2), 16));
    }
    buff.rewind();
    Charset cs = Charset.forName("UTF-8");
    CharBuffer cb = cs.decode(buff);
    return cb.toString();
}
 
Example 10
Source File: NIODemo5.java    From cs-summary-reflection with Apache License 2.0 5 votes vote down vote up
@Test
public void test6() throws IOException {
    Charset cs1 = Charset.forName("UTF-8");

    // 获取编码器
    CharsetEncoder ce = cs1.newEncoder();

    // 获取解码器
    CharsetDecoder cd = cs1.newDecoder();

    CharBuffer cBuf = CharBuffer.allocate(1024);
    cBuf.put("哈哈哈哈!");
    cBuf.flip();

    // 编码
    ByteBuffer bBuf = ce.encode(cBuf);

    for (int i = 0; i < 12; i++) {
        System.out.println(bBuf.get());
    }

    // 解码
    bBuf.flip();
    CharBuffer cBuf2 = cd.decode(bBuf);
    System.out.println(cBuf2.toString());

    System.out.println("------------------------------------------------------");
    // 乱码
    Charset cs2 = Charset.forName("GBK");
    bBuf.flip();
    CharBuffer cBuf3 = cs2.decode(bBuf);
    System.out.println(cBuf3.toString());
}
 
Example 11
Source File: Utf7.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Convert string from UTF-7 characters
 * 
 * @param string Input string for decoding
 * @return Decoded string
 */
public static String decode(String string, String charsetName)
{
    if (string.length() <= 1)
    {
        return string;
    }
    CharsetProvider provider = new CharsetProvider();
    Charset charset = provider.charsetForName(charsetName);
    CharBuffer charBuffer = charset.decode(ByteBuffer.wrap(string.getBytes()));
    return charBuffer.toString();
}
 
Example 12
Source File: AbstractScheduledInput.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
protected static Object convert ( final byte[] data, final Charset charset )
{
    if ( data == null )
    {
        return null;
    }

    if ( charset == null )
    {
        return data;
    }

    final CharBuffer cb = charset.decode ( ByteBuffer.wrap ( data ) );
    return cb.toString ();
}
 
Example 13
Source File: ConversionUtils.java    From RxFingerprint with Apache License 2.0 5 votes vote down vote up
static char[] toChars(byte[] bytes) {
  Charset charset = Charset.forName("UTF-8");
  ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
  CharBuffer charBuffer = charset.decode(byteBuffer);
  char[] chars = Arrays.copyOf(charBuffer.array(), charBuffer.limit());

  Arrays.fill(charBuffer.array(), '\u0000'); // clear the cleartext
  Arrays.fill(byteBuffer.array(), (byte) 0); // clear the ciphertext

  return chars;
}
 
Example 14
Source File: CharsetTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private void assertDecodes(Charset cs, String s, int... byteInts) throws Exception {
  ByteBuffer in = ByteBuffer.wrap(toByteArray(byteInts));
  CharBuffer out = cs.decode(in);
  assertEquals(s, out.toString());
}
 
Example 15
Source File: FragmentEncoder.java    From compliance with Apache License 2.0 4 votes vote down vote up
private static String decode(String s, Charset charset) {

      char[] str_buf = new char[s.length()];
      byte[] buf = new byte[s.length() / 3];
      int buf_len = 0;

      for (int i = 0; i < s.length();) {
          char c = s.charAt(i);
          if (c == '+') {
              str_buf[buf_len] = ' ';
          } else if (c == '%') {

              int len = 0;
              do {
                  if (i + 2 >= s.length()) {
                      throw new IllegalArgumentException(
                              "Incomplete % sequence at: " + i);
                  }
                  int d1 = Character.digit(s.charAt(i + 1), 16);
                  int d2 = Character.digit(s.charAt(i + 2), 16);
                  if (d1 == -1 || d2 == -1) {
                      throw new IllegalArgumentException(
                              "Invalid % sequence "
                                      + s.substring(i, i + 3)
                                      + " at " + i);
                  }
                  buf[len++] = (byte) ((d1 << 4) + d2);
                  i += 3;
              } while (i < s.length() && s.charAt(i) == '%');

              CharBuffer cb = charset.decode(ByteBuffer.wrap(buf, 0, len));
              len = cb.length();
              System.arraycopy(cb.array(), 0, str_buf, buf_len, len);
              buf_len += len;
              continue;
          } else {
              str_buf[buf_len] = c;
          }
          i++;
          buf_len++;
      }
      return new String(str_buf, 0, buf_len);
  }
 
Example 16
Source File: CharsetTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testDecode_Malformed() throws Exception {
  Charset c1 = Charset.forName("iso8859-1");
  CharBuffer cb = c1.decode(ByteBuffer.wrap("abcd\u5D14efg".getBytes("iso8859-1")));
  byte[] replacement = c1.newEncoder().replacement();
  assertEquals(new String(cb.array()).trim(), "abcd" + new String(replacement, "iso8859-1") + "efg");
}
 
Example 17
Source File: DirWatcher.java    From LiveDirsFX with BSD 2-Clause "Simplified" License 4 votes vote down vote up
private String readTextFile(Path file, Charset charset) throws IOException {
    byte[] bytes = Files.readAllBytes(file);
    CharBuffer chars = charset.decode(ByteBuffer.wrap(bytes));
    return chars.toString();
}
 
Example 18
Source File: String.java    From juniversal with MIT License 4 votes vote down vote up
/**
 * Converts the byte array to a String using the specified encoding.
 * 
 * @param data
 *            the byte array to convert to a String
 * @param start
 *            the starting offset in the byte array
 * @param length
 *            the number of bytes to convert
 * @param encoding
 *            the encoding
 * 
 * @throws IndexOutOfBoundsException
 *             when <code>length < 0, start < 0</code> or
 *             <code>start + length > data.length</code>
 * @throws NullPointerException
 *             when data is null
 * 
 * @see #getBytes()
 * @see #getBytes(int, int, byte[], int)
 * @see #getBytes(String)
 * @see #valueOf(boolean)
 * @see #valueOf(char)
 * @see #valueOf(char[])
 * @see #valueOf(char[], int, int)
 * @see #valueOf(double)
 * @see #valueOf(float)
 * @see #valueOf(int)
 * @see #valueOf(long)
 * @see #valueOf(Object)
 * @since 1.6
 */
public String(byte[] data, int start, int length, final Charset encoding) {
    if (encoding == null) {
        throw new NullPointerException();
    }
    // start + length could overflow, start/length maybe MaxInt
    if (start >= 0 && 0 <= length && length <= data.length - start) {
        offset = 0;
        lastCharset = encoding;
        
        CharBuffer cb = encoding
                .decode(ByteBuffer.wrap(data, start, length));
        value = cb.array();
        count = cb.length();
    } else {
        throw new StringIndexOutOfBoundsException();
    }
}
 
Example 19
Source File: Converter.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
static public char[] convertByteToCharUTF(byte[] byteArray) {
    Charset c = CDM.utf8Charset;
    CharBuffer output = c.decode(ByteBuffer.wrap(byteArray));
    return output.array();
}
 
Example 20
Source File: IospHelper.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static char[] convertByteToCharUTF(byte[] byteArray) {
  Charset c = StandardCharsets.UTF_8;
  CharBuffer output = c.decode(ByteBuffer.wrap(byteArray));
  return output.array();
}