|
| 1 | +package org.baeldung.java.io; |
| 2 | + |
| 3 | + |
| 4 | +import com.google.common.io.ByteStreams; |
| 5 | +import org.apache.commons.io.IOUtils; |
| 6 | +import org.junit.jupiter.api.Test; |
| 7 | + |
| 8 | +import java.io.File; |
| 9 | +import java.io.FileInputStream; |
| 10 | +import java.io.IOException; |
| 11 | +import java.nio.ByteBuffer; |
| 12 | +import java.nio.channels.ReadableByteChannel; |
| 13 | + |
| 14 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 15 | + |
| 16 | +class InputStreamToByteBufferUnitTest { |
| 17 | + |
| 18 | + @Test |
| 19 | + public void givenUsingCoreClasses_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException { |
| 20 | + File inputFile = getFile(); |
| 21 | + ByteBuffer bufferByte = ByteBuffer.allocate((int) inputFile.length()); |
| 22 | + FileInputStream in = new FileInputStream(inputFile); |
| 23 | + in.getChannel().read(bufferByte); |
| 24 | + |
| 25 | + assertEquals(bufferByte.position(), inputFile.length()); |
| 26 | + } |
| 27 | + |
| 28 | + @Test |
| 29 | + public void givenUsingCommonsIo_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException { |
| 30 | + File inputFile = getFile(); |
| 31 | + ByteBuffer bufferByte = ByteBuffer.allocateDirect((int) inputFile.length()); |
| 32 | + ReadableByteChannel readableByteChannel = new FileInputStream(inputFile).getChannel(); |
| 33 | + IOUtils.readFully(readableByteChannel, bufferByte); |
| 34 | + |
| 35 | + assertEquals(bufferByte.position(), inputFile.length()); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + public void givenUsingGuava_whenWritingAFileIntoAByteBuffer_thenBytesLengthMustMatch() throws IOException { |
| 40 | + File inputFile = getFile(); |
| 41 | + FileInputStream in = new FileInputStream(inputFile); |
| 42 | + byte[] targetArray = ByteStreams.toByteArray(in); |
| 43 | + ByteBuffer bufferByte = ByteBuffer.wrap(targetArray); |
| 44 | + bufferByte.rewind(); |
| 45 | + while (bufferByte.hasRemaining()) { |
| 46 | + bufferByte.get(); |
| 47 | + } |
| 48 | + |
| 49 | + assertEquals(bufferByte.position(), inputFile.length()); |
| 50 | + } |
| 51 | + |
| 52 | + private File getFile() { |
| 53 | + ClassLoader classLoader = new InputStreamToByteBufferUnitTest().getClass().getClassLoader(); |
| 54 | + |
| 55 | + String fileName = "frontenac-2257154_960_720.jpg"; |
| 56 | + |
| 57 | + return new File(classLoader.getResource(fileName).getFile()); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments