java.nio.charset.Charset#decode ( )源码实例Demo

下面列出了java.nio.charset.Charset#decode ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TrackRay   文件: WebsocketOutputStream.java

@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();
            }
        }
    }
}
 
源代码2 项目: netbeans   文件: Utils.java

/**
    * 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;
}
 
源代码3 项目: juniversal   文件: String.java

/**
 * 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();
    }
}
 
源代码4 项目: jphp   文件: StrUtils.java

@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());
}
 
源代码5 项目: juniversal   文件: String.java

/**
 * 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();
    }
}
 

@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;
}
 
源代码7 项目: TrackRay   文件: PluginDataOutputStream.java

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);

}
 
源代码8 项目: gsc-core   文件: Utils.java

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();
}
 
源代码9 项目: alpha-wallet-android   文件: Hex.java

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();
}
 
源代码10 项目: cs-summary-reflection   文件: NIODemo5.java

@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());
}
 
源代码11 项目: alfresco-repository   文件: Utf7.java

/**
 * 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();
}
 
源代码12 项目: neoscada   文件: AbstractScheduledInput.java

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 ();
}
 
源代码13 项目: RxFingerprint   文件: ConversionUtils.java

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;
}
 
源代码14 项目: netcdf-java   文件: IospHelper.java

public static char[] convertByteToCharUTF(byte[] byteArray) {
  Charset c = StandardCharsets.UTF_8;
  CharBuffer output = c.decode(ByteBuffer.wrap(byteArray));
  return output.array();
}
 
源代码15 项目: MeteoInfo   文件: Converter.java

static public char[] convertByteToCharUTF(byte[] byteArray) {
    Charset c = CDM.utf8Charset;
    CharBuffer output = c.decode(ByteBuffer.wrap(byteArray));
    return output.array();
}
 
源代码16 项目: juniversal   文件: String.java

/**
 * 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();
    }
}
 
源代码17 项目: LiveDirsFX   文件: DirWatcher.java

private String readTextFile(Path file, Charset charset) throws IOException {
    byte[] bytes = Files.readAllBytes(file);
    CharBuffer chars = charset.decode(ByteBuffer.wrap(bytes));
    return chars.toString();
}
 
源代码18 项目: j2objc   文件: CharsetTest.java

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");
}
 
源代码19 项目: compliance   文件: FragmentEncoder.java

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);
  }
 
源代码20 项目: j2objc   文件: CharsetTest.java

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());
}