|
| 1 | +package com.baeldung.outputstreamtobytearray; |
| 2 | + |
| 3 | +import org.apache.commons.io.FileUtils; |
| 4 | +import org.junit.jupiter.api.Assertions; |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | + |
| 7 | +import java.io.*; |
| 8 | + |
| 9 | +public class OutputStreamtoByteArrayUnitTest { |
| 10 | + |
| 11 | + @Test |
| 12 | + public void givenFileOutputStream_whenUsingFileUtilsToReadTheFile_thenReturnByteArray() throws IOException { |
| 13 | + String data = "Welcome to Baeldung!"; |
| 14 | + String filePath = "file.txt"; |
| 15 | + |
| 16 | + try (FileOutputStream outputStream = new FileOutputStream(filePath)) { |
| 17 | + outputStream.write(data.getBytes()); |
| 18 | + } |
| 19 | + |
| 20 | + byte[] byteArray = FileUtils.readFileToByteArray(new File(filePath)); |
| 21 | + String result = new String(byteArray); |
| 22 | + |
| 23 | + Assertions.assertEquals(data, result); |
| 24 | + } |
| 25 | + |
| 26 | + |
| 27 | + @Test |
| 28 | + public void givenFileOutputStream_whenUsingDrainableOutputStream_thenReturnByteArray() throws IOException { |
| 29 | + String data = "Welcome to Baeldung!"; |
| 30 | + String filePath = "file.txt"; |
| 31 | + DrainableOutputStream drainableOutputStream = new DrainableOutputStream(new FileOutputStream(filePath)); |
| 32 | + drainableOutputStream.write(data.getBytes()); |
| 33 | + byte[] intercepted = drainableOutputStream.toByteArray(); |
| 34 | + String result = new String(intercepted); |
| 35 | + Assertions.assertEquals(data, result); |
| 36 | + } |
| 37 | + |
| 38 | + public class DrainableOutputStream extends FilterOutputStream { |
| 39 | + private final ByteArrayOutputStream buffer; |
| 40 | + |
| 41 | + public DrainableOutputStream(OutputStream out) { |
| 42 | + super(out); |
| 43 | + this.buffer = new ByteArrayOutputStream(); |
| 44 | + } |
| 45 | + |
| 46 | + @Override |
| 47 | + public void write(byte b[]) throws IOException { |
| 48 | + this.buffer.write(b); |
| 49 | + super.write(b); |
| 50 | + } |
| 51 | + |
| 52 | + public byte[] toByteArray() { |
| 53 | + return this.buffer.toByteArray(); |
| 54 | + } |
| 55 | + } |
| 56 | +} |