Java - matriz de bytes para o gravador

Java - matriz de bytes para o gravador

1. Visão geral

Neste tutorial muito rápido, discutiremos como converterbyte[] to Writer usando Java simples, Guava e Commons IO.

2. Com Plain Java

Vamos começar com uma solução Java simples:

@Test
public void givenPlainJava_whenConvertingByteArrayIntoWriter_thenCorrect()
  throws IOException {
    byte[] initialArray = "With Java".getBytes();
    Writer targetWriter = new StringWriter().append(new String(initialArray));

    targetWriter.close();

    assertEquals("With Java", targetWriter.toString());
}

Observe que convertemos nossobyte[] em aWriter por meio de umString intermediário.

3. Com goiaba

A seguir - vamos examinar uma solução mais complexa com Guava:

@Test
public void givenUsingGuava_whenConvertingByteArrayIntoWriter_thenCorrect()
  throws IOException {
    byte[] initialArray = "With Guava".getBytes();

    String buffer = new String(initialArray);
    StringWriter stringWriter = new StringWriter();
    CharSink charSink = new CharSink() {
        @Override
        public Writer openStream() throws IOException {
            return stringWriter;
        }
    };
    charSink.write(buffer);

    stringWriter.close();

    assertEquals("With Guava", stringWriter.toString());
}

Observe que aqui, convertemosbyte[] emWriter usandoCharSink.

4. Com Commons IO

Por fim, vamos verificar nossa solução Commons IO:

@Test
public void givenUsingCommonsIO_whenConvertingByteArrayIntoWriter_thenCorrect()
  throws IOException {
    byte[] initialArray = "With Commons IO".getBytes();

    Writer targetWriter = new StringBuilderWriter(
      new StringBuilder(new String(initialArray)));

    targetWriter.close();

    assertEquals("With Commons IO", targetWriter.toString());
}

Nota: Convertemos nossobyte[] emStringBuilderWriter usando umStringBuilder.

5. Conclusão

Neste tutorial curto e direto, ilustramos 3 maneiras diferentes de converter abyte[] emWriter.

O código deste artigo está disponível emthe GitHub repository.