|
1 | 1 | package net.tootallnate.websocket; |
2 | 2 |
|
3 | 3 | import java.io.UnsupportedEncodingException; |
| 4 | +import java.nio.ByteBuffer; |
| 5 | +import java.nio.charset.CharacterCodingException; |
| 6 | +import java.nio.charset.Charset; |
| 7 | +import java.nio.charset.CharsetDecoder; |
| 8 | +import java.nio.charset.CodingErrorAction; |
4 | 9 |
|
5 | 10 | public class Charsetfunctions { |
6 | 11 |
|
| 12 | + public static CodingErrorAction codingErrorAction = CodingErrorAction.REPORT; |
| 13 | + |
7 | 14 | /* |
8 | 15 | * @return UTF-8 encoding in bytes |
9 | 16 | */ |
@@ -34,19 +41,17 @@ public static String stingAscii( byte[] bytes ) { |
34 | 41 | } |
35 | 42 | } |
36 | 43 |
|
37 | | - public static String stingAscii( byte[] bytes, int offset, int length ) { |
| 44 | + public static String stingAscii( byte[] bytes, int offset, int length ){ |
38 | 45 | try { |
39 | 46 | return new String( bytes, offset, length, "ASCII" ); |
40 | 47 | } catch ( UnsupportedEncodingException e ) { |
41 | 48 | throw new RuntimeException( e ); |
42 | 49 | } |
43 | 50 | } |
44 | 51 |
|
45 | | - public static String stingUtf8( byte[] bytes ) { |
46 | | - try { |
47 | | - return new String( bytes, "UTF8" ); |
48 | | - } catch ( UnsupportedEncodingException e ) { |
49 | | - throw new RuntimeException( e ); |
50 | | - } |
| 52 | + public static String stingUtf8( byte[] bytes ) throws CharacterCodingException { |
| 53 | + CharsetDecoder encode = Charset.forName("UTF8").newDecoder(); |
| 54 | + encode.onMalformedInput( codingErrorAction ); |
| 55 | + return encode.decode( ByteBuffer.wrap( bytes ) ).toString(); |
51 | 56 | } |
52 | 57 | } |
0 commit comments