本文共 3860 字,大约阅读时间需要 12 分钟。
byte[] original1 = new byte[]{(byte)0xef, (byte)0x8f, (byte)0x8f};byte[] transformed1 = new String(original1).getBytes();System.out.println(Arrays.toString(original1));System.out.println(Arrays.toString(transformed1));System.out.println(Arrays.equals(original1, transformed1));
[-17, -113, -113][-17, -113, -113]true
byte[] original2 = new byte[]{(byte)0xef, (byte)0x8f, (byte)0xff};byte[] transformed2 = new String(original2).getBytes();System.out.println(Arrays.toString(original2));System.out.println(Arrays.toString(transformed2));System.out.println(Arrays.equals(original2, transformed2));
[-17, -113, -1][-17, -65, -67, -17, -65, -67]false
byte[] original2 = new byte[]{(byte)0xef, (byte)0x8f, (byte)0xff};// 根据指定的编码查找CharsetCharset charset = Charset.forName("utf-8");// 初始化对应charset的decoderCharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE);// 使用decoder对字节进行编码转换decoder.decode(ByteBuffer.wrap(original2));
String replaceChar = "\uFFFD";System.out.println(Arrays.toString(replaceChar.getBytes("utf-8")));输出结果:[-17, -65, -67]
byte[] original2 = new byte[]{(byte)0xef, (byte)0x8f, (byte)0xff};Charset charset = Charset.forName("utf-8");CharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT);decoder.decode(ByteBuffer.wrap(original2));输出结果:Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 2 at java.nio.charset.CoderResult.throwException(CoderResult.java:260) at java.nio.charset.CharsetDecoder.decode(CharsetDecoder.java:781)......那如果我们就想把一段bytes解码为String,再从String编码为bytes,要保证bytes能正确的转换回来,应该怎么做呢?
byte[] original2 = new byte[]{(byte)0xef, (byte)0x8f, (byte)0xff};byte[] transformed2 = new String(original2, "iso-8859-1").getBytes("iso-8859-1");System.out.println(Arrays.toString(original2));System.out.println(Arrays.toString(transformed2));System.out.println(Arrays.equals(original2, transformed2));
转载地址:http://jaybx.baihongyu.com/