From 94ddcd153d6431d5aa4b3c84b97c9636f6a3219f Mon Sep 17 00:00:00 2001 From: DiegoMarti2 <150871541+DiegoMarti2@users.noreply.github.com> Date: Sun, 10 Dec 2023 19:40:01 +0200 Subject: [PATCH] baeldung-articles : BAEL-6892 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commit to adding two mеthods to convert OutputStream to a byte array. --- .../OutputStreamtoByteArrayUnitTest.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 core-java-modules/core-java-io-5/src/test/java/com/baeldung/outputstreamtobytearray/OutputStreamtoByteArrayUnitTest.java diff --git a/core-java-modules/core-java-io-5/src/test/java/com/baeldung/outputstreamtobytearray/OutputStreamtoByteArrayUnitTest.java b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/outputstreamtobytearray/OutputStreamtoByteArrayUnitTest.java new file mode 100644 index 0000000000..2e46a5c571 --- /dev/null +++ b/core-java-modules/core-java-io-5/src/test/java/com/baeldung/outputstreamtobytearray/OutputStreamtoByteArrayUnitTest.java @@ -0,0 +1,56 @@ +package com.baeldung.outputstreamtobytearray; + +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.*; + +public class OutputStreamtoByteArrayUnitTest { + + @Test + public void givenFileOutputStream_whenUsingFileUtilsToReadTheFile_thenReturnByteArray() throws IOException { + String data = "Welcome to Baeldung!"; + String filePath = "file.txt"; + + try (FileOutputStream outputStream = new FileOutputStream(filePath)) { + outputStream.write(data.getBytes()); + } + + byte[] byteArray = FileUtils.readFileToByteArray(new File(filePath)); + String result = new String(byteArray); + + Assertions.assertEquals(data, result); + } + + + @Test + public void givenFileOutputStream_whenUsingDrainableOutputStream_thenReturnByteArray() throws IOException { + String data = "Welcome to Baeldung!"; + String filePath = "file.txt"; + DrainableOutputStream drainableOutputStream = new DrainableOutputStream(new FileOutputStream(filePath)); + drainableOutputStream.write(data.getBytes()); + byte[] intercepted = drainableOutputStream.toByteArray(); + String result = new String(intercepted); + Assertions.assertEquals(data, result); + } + + public class DrainableOutputStream extends FilterOutputStream { + private final ByteArrayOutputStream buffer; + + public DrainableOutputStream(OutputStream out) { + super(out); + this.buffer = new ByteArrayOutputStream(); + } + + @Override + public void write(byte b[]) throws IOException { + this.buffer.write(b); + super.write(b); + } + + public byte[] toByteArray() { + return this.buffer.toByteArray(); + } + } +}