CharsetEncodingUtils { public static byte[] encodeAsUTF8(String input) throws IOException { CharsetEncoder e = CSE.get(); e.reset(); return bytes(e.encode(CharBuffer.wrap(input.toCharArray()))); } private  CharsetEncodingUtils(); static byte[] encodeAsUTF8(String input);  }
@Test public void encodeValid() throws IOException { String test = "a \u00E4 \u20ac " + new String(SURROGATE_PAIR); byte[] withStringClass = test.getBytes(StandardCharsets.UTF_8); byte[] withUtilsClass = CharsetEncodingUtils.encodeAsUTF8(test); assertArrayEquals(withStringClass, withUtilsClass); assertEquals(test, new String(withUtilsClass, StandardCharsets.UTF_8)); }
@Test public void encodeInValid() { String test = "a \u00E4 \u20ac " + SURROGATE_PAIR[0]; try { CharsetEncodingUtils.encodeAsUTF8(test); fail("expected encoding to fail"); } catch (IOException expected) { } }
@Test public void encodeMultiThreaded() throws InterruptedException { int tc = 20; Thread[] threads = new Thread[tc]; for (int i = 0; i < tc; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 100; j++) { String test = UUID.randomUUID().toString(); String roundtripped = null; try { byte[] bytes = CharsetEncodingUtils.encodeAsUTF8(test); roundtripped = new String(bytes, StandardCharsets.UTF_8); } catch (IOException exignored) { } assertEquals(test, roundtripped); } } }); } for (int i = 0; i < tc; i++) { threads[i].start(); } for (int i = 0; i < tc; i++) { threads[i].join(); } }